var scrollpool = 0;
var prevnexttimer;
var blockenter = 0;
var hcstatstimer;
var signuptimer;
var signupproceed = 0;
var blockentertimer;
var store_prevnext_prev = 0;
var store_prevnext_next = 0;
var lastopenedphoto = '';
var lastopenurl = '';
var savingmethod = 0;
var messenger_writing = 0;
var tunermode = '0';
var hcshowallphotos = 0;
var originalsuggestions = '';
var stopscroll = '0';
var openmsg = '';
var msgopen = '';
var mainsearch_cache = '';
var mainsearch_timer;
var contest_action = '';
var modalopen = '';
var curate_load = 0;
var retainmodal = '';
var switching_theme = 0;
var themetimer;
var foundsplash = 0;
var nottimer;
var changetheme = new Object();
var themeani = 700;
var menu = 0;
var search_cache = '';
var lastscrollpos = 0;
var automenu = 1;
var menutimer;
var sorttimer;
var data_loading = 0;
var blockmenuhide = 1;
var blockmenushow = 1;
var blockenablemenu = 1;
var searchtimer;
var scrollposition = 0;
var leftminiactive = 0;
var loadmore = '0';
var loadmorelooptimer;
var loadmoreindicator;
var loadmoreblock = '0';
var loadmore_overview = '0';
var loadmoreblock_overview = '0';
var re_order = '';
var progresstimer;
var progresstimer2;
var axp = 0;
var startxp = 0;
var curateload;
var totalcurate = 0;
var totalcurate2 = 0;
var curatemessagetimer;
var curatesession = 0;
var curateresume_what = '';
var curateresume_id = '';
var curateresume_did = '';
var starblock = 0;
var cc = '';
var centermessagetimer;
var blockarrows = 0;
var tagging_undo_modal = '';
var tagging_undo_picid = '';
var tagging_undo_phaseid = '';

doinggreat = new Array;
doinggreat[0] = "You are doing great!";
doinggreat[1] = "Excellent work!";
doinggreat[2] = "Well done so far!";
doinggreat[3] = "Good job, keep voting to reach the next level";

setTimeout('blockmenuhide=0;', 200);
setTimeout('blockenablemenu=0;', 800);

$(document).bind('keyup', function (e) {
        var evtobj = window.event ? event : e //distinguish between IE's explicit event object (window.event) and Firefox's implicit.
        var unicode = evtobj.charCode ? evtobj.charCode : evtobj.keyCode
        var actualkey = String.fromCharCode(unicode)

        var modalopena = modalopen.split(":");
        if (modalopena[0] == "tagging") {
                if (document.getElementById('tagging-addtag') != null) {
                        if (document.getElementById('tagging-addtag').value == '') {
                                if (evtobj.keyCode == 13) {
                                        //if(blockenter == 0) { taggingSave(); }
                                }
                        } else {
                                //clearTimeout(blockentertimer);
                        }
                }
                if (evtobj.keyCode == 27) {
                        closeModal();
                }
                if (document.getElementById('tagging-addtag') == null) {
                        if (evtobj.keyCode == 32) {
                                taggingSave();
                        }
                }
                if (document.getElementById('grade_1') != null) {
                        if (evtobj.keyCode == 49) {
                                document.getElementById('grade_1').checked = 1;
                                setTimeout('taggingSave();', 100);
                        }
                        if (evtobj.keyCode == 50) {
                                document.getElementById('grade_2').checked = 1;
                                setTimeout('taggingSave();', 100);
                        }
                        if (evtobj.keyCode == 51) {
                                document.getElementById('grade_3').checked = 1;
                                setTimeout('taggingSave();', 100);
                        }
                        if (evtobj.keyCode == 52) {
                                document.getElementById('grade_4').checked = 1;
                                setTimeout('taggingSave();', 100);
                        }
                        if (evtobj.keyCode == 53) {
                                document.getElementById('grade_5').checked = 1;
                                setTimeout('taggingSave();', 100);
                        }
                        if (evtobj.keyCode == 54) {
                                document.getElementById('grade_6').checked = 1;
                                setTimeout('taggingSave();', 100);
                        }
                }
                if (document.getElementById('mgrade_1') != null) {
                        if (evtobj.keyCode == 49) {
                                document.getElementById('mgrade_1').checked = 1;
                                setTimeout('taggingSave();', 100);
                        }
                        if (evtobj.keyCode == 50) {
                                document.getElementById('mgrade_2').checked = 1;
                                setTimeout('taggingSave();', 100);
                        }
                        if (evtobj.keyCode == 51) {
                                document.getElementById('mgrade_3').checked = 1;
                                setTimeout('taggingSave();', 100);
                        }
                }
        }

        if (modalopena[0] == "headcuration") {
                if (blockarrows == 0) {
                        if (evtobj.keyCode == 27) {
                                if (hcshowallphotos == 0) {
                                        closeModal();
                                } else {
                                        hcCloseShowPhotos(hcshowallphotos);
                                }
                        }

                        if (evtobj.keyCode == 37) {
                                if (document.getElementById('hc_prev') != null) {
                                        hcPrev();
                                }
                        }
                        if (evtobj.keyCode == 39 || evtobj.keyCode == 32) {
                                if (document.getElementById('hc_next') != null) {
                                        hcNext();
                                }
                        }
                }
        }
});

function coverpos(what, direction) {
        var currvalue = parseInt(document.getElementById('coverpos-' + what).value);
        if (direction == 'up') { currvalue = currvalue - 5; }
        if (direction == 'down') { currvalue = currvalue + 5; }
        if (direction == 'upq') { currvalue = currvalue - 15; }
        if (direction == 'downq') { currvalue = currvalue + 15; }
        if (currvalue < 0) { currvalue = 0; }
        if (currvalue > 100) { currvalue = 100; }
        $('#cover-' + what).css("background-position", "center " + currvalue + "%");
        document.getElementById('coverpos-' + what).value = currvalue;
}

function centermessage(message, timeout) {
        clearTimeout(centermessagetimer);
        $('#main-message').html(message);
        $('#main-message').css("display", "block"); // fadeIn();
        $('#main-message').css("marginLeft", "-" + ($('#main-message').width() / 2) + "px");
        centermessagetimer = setTimeout('$(\'#main-message\').fadeOut();', timeout);
}

function mainsearch() {
        clearTimeout(mainsearch_timer);
        var search_q = document.getElementById('search-input').value;
        if (search_q.length > 2) {
                $('#search-info').html('Searching for "' + search_q + '"');
                mainsearch_timer = setTimeout('mainsearchdo();', 1000);
        } else {
                $('#photos-feed').html('<div class="type-to-start-searching">Type to start searching</div>');
                $('#search-info').html('');
                mainsearch_cache = '';
                history.replaceState('', '', '/search');
        }
}

function mainsearchdo() {
        var search_q = document.getElementById('search-input').value;
        if (search_q != mainsearch_cache) {
                if (search_q.length > 2) {
                        document.getElementById('lm_active').value = '1';
                        document.getElementById('lm_from').value = '0';
                        document.getElementById('lm_search').value = search_q;
                        $('#gallery-loadmore').css("opacity", "1");
                        $('#photos-feed').html('');
                        doLoadmore();
                        mainsearch_cache = search_q;
                        history.replaceState('', '', '/search/' + search_q);
                } else {
                        $('#photos-feed').html('<div class="type-to-start-searching">Type to start searching</div>');
                        mainsearch_cache = '';
                        history.replaceState('', '', '/search');
                }
        }
}

function setpurp(what) {
        if (document.getElementById(what) != null) {
                if (document.getElementById(what).value == '1') {
                        document.getElementById(what).value = '0';
                        $('#' + what + '_icon').removeClass("purpose-why-check-active");
                        $('#' + what + '_icon').addClass("purpose-why-check-inactive");
                        $('#' + what + '_why').removeClass("purpose-why-active");
                } else {
                        document.getElementById(what).value = '1';
                        $('#' + what + '_icon').addClass("purpose-why-check-active");
                        $('#' + what + '_icon').removeClass("purpose-why-check-inactive");
                        $('#' + what + '_why').addClass("purpose-why-active");
                }
                if (document.getElementById('purp_exposure').value == '1' || document.getElementById('purp_sell').value == '1' || document.getElementById('purp_learn').value == '1' || document.getElementById('purp_look').value == '1' || document.getElementById('purp_inspire').value == '1') {
                        $('#savepurpose').css("opacity", "1");
                } else {
                        $('#savepurpose').css("opacity", ".3");
                }
        }
}

function hcExec(id, decision) {
        var proceed = 1;
        var execute_decision = '';

        if (decision == '3' && document.getElementById('hc_noreject').value == '1') {
                proceed = 0;
        }

        if (document.getElementById('hc_nodecision').value == '0') {
                if (decision == '3' || decision == '4' || decision == '5') {
                        if (proceed == 1) {
                                if (decision == '4') { centermessage('You have published #' + id, 2000); }
                                if (decision == '5') { centermessage('You have awarded #' + id, 2000); }
                                if (decision == '3') { centermessage('#' + id + ' not awarded', 2000); }
                                execute_decision = decision;
                                $('#hc_' + id).remove();
                                setTimeout('hcStatistics();', 2000);
                                hcCurNext();
                        } else {
                                alert('Your award rate must be 10% or above');
                        }
                }

                if (decision == 'lock') {
                        if (document.getElementById('lockbutton_' + id).innerHTML == 'Unlock') {
                                centermessage('#' + id + ' is now unlocked', 2000);
                                document.getElementById('lockbutton_' + id).innerHTML = 'Lock';
                                execute_decision = 'unlock';
                        } else {
                                centermessage('#' + id + ' is now locked to you', 2000);
                                document.getElementById('lockbutton_' + id).innerHTML = 'Unlock';
                                execute_decision = 'lock';
                        }
                }
        } else {
                if (document.getElementById('hc_nodecision').value == '1') {
                        alert('You have curated over 1000 images last week and hit the limit. No decisions can be taken at this time.');
                }
                if (document.getElementById('hc_nodecision').value == '2') {
                        alert('Please wait until the image data has loaded');
                }
        }

        if (execute_decision != '') {
                $.ajax({
                        type: "GET",
                        url: "/backend/hcexec.php?id=" + id + "&execute=" + execute_decision,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                        } else { alert(status); }
                                });
                        }
                });
        }
}

function getexhibitioncomments(id) {
        if (parseInt(id) > 0) {
                $.ajax({
                        type: "GET",
                        url: "/backend/exhibitioncomments.php?id=" + id,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var data = $(this).find('data').text();
                                        if (status == 'OK') {
                                                $('#exhibition-comments').html(data);
                                        } else { alert(status); }
                                });
                        }
                });
        }
}

function regenerateCert(id) {
        $.ajax({
                type: "GET",
                url: "/backend/certgenerate.php?id=" + id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        $('#rc-' + id).remove();
                                        alert('Certificate will be regenerated and available in 1x.com/certificates shortly');
                                } else { alert(status); }
                        });
                }
        });

}

function hcdeleted() {
        if (document.getElementById('headcuration-main') != null) {
                $.ajax({
                        type: "GET",
                        url: "/backend/hcdeleted.php",
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var data = $(this).find('data').text();
                                        if (status == 'OK') {
                                                var deleteda = JSON.parse(data);
                                                for (const [key, value] of Object.entries(deleteda)) {
                                                        if (parseInt(key) > 0) {
                                                                if (document.getElementById('hc_' + key) != null) {
                                                                        $('#hc_' + key).remove();
                                                                }
                                                        }
                                                }
                                                setTimeout('hcdeleted();', 30000);
                                        }
                                });
                        }
                });
        }
}

function setCuratorTest(pic_id, score) {
        $.ajax({
                type: "GET",
                url: "/backend/curatortest.php?pic_id=" + pic_id + "&score=" + score,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        if (score == '0') {
                                                if (document.getElementById('curatortest-image-' + pic_id) != null) {
                                                        $('#curatortest-image-' + pic_id).fadeOut();
                                                }
                                        }

                                } else { alert(status); }
                        });
                }
        });

}

function reportComment(id, what) {
        if (what == 'photos') {
                $.ajax({
                        type: "GET",
                        url: "/backend/reportcomment.php?id=" + id + "&what=" + what,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                document.getElementById('comment-' + id).innerHTML = '<i>Comment has been reported</i>';
                                                document.getElementById('photo-detail-comment-replybutton-' + id).style.display = 'none';
                                        } else { alert(status); }
                                });
                        }
                });
        }
        if (what == 'feedbacks') {
                $.ajax({
                        type: "GET",
                        url: "/backend/reportcomment.php?id=" + id + "&what=" + what,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                document.getElementById('feedbacks-' + id).innerHTML = '<i>Comment has been reported</i>';
                                        } else { alert(status); }
                                });
                        }
                });
        }
        if (what == 'critique') {
                $.ajax({
                        type: "GET",
                        url: "/backend/reportcomment.php?id=" + id + "&what=" + what,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                document.getElementById('critique-' + id).innerHTML = '<i>Comment has been reported</i>';
                                        } else { alert(status); }
                                });
                        }
                });
        }
}

function handleReport(whata, id, decision) {
        $.ajax({
                type: "GET",
                url: "/backend/handlereport.php?id=" + id + "&what=" + whata + "&decision=" + decision,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        document.getElementById(whata + id).style.display = 'none';
                                } else { alert(status); }
                        });
                }
        });
}


function newagr(decision) {
        if (decision == '1' || decision == '2') {
                $.ajax({
                        type: "GET",
                        url: "/backend/newagr.php?decision=" + decision,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                closeModal();
                                                if (decision == '2') {
                                                        location.href = '/';
                                                }
                                        } else { alert(status); }
                                });
                        }
                });
        }
}

function blockPartners(user_id, blockstr) {
        $.ajax({
                type: "GET",
                url: "/backend/blockpartners.php?user_id=" + user_id + "&block=" + blockstr,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var blockc = $(this).find('blockc').text();
                                if (status == 'OK') {
                                        closeModal();
                                        $('#blockc').html(blockc);
                                } else { alert(status); }
                        });
                }
        });


}

function deleteCover(id) {
        $.ajax({
                type: "GET",
                url: "/backend/deletecover.php?id=" + id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        location.href = location.href;
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}


function saveCover(id, imgfile) {
        $.ajax({
                type: "GET",
                url: "/backend/savecover.php?id=" + id + "&imgfile=" + imgfile + "&pos_computer=" + document.getElementById('coverpos-computer').value + "&pos_mobile=" + document.getElementById('coverpos-mobile').value + "&color=" + document.getElementById('cover_textcolor').value,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        centermessage('Cover is set', 2000);
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function magazineAddPhoto() {
        if (parseInt(document.getElementById('magazine-add-photo-id').value) > 0) {
                $.ajax({
                        type: "GET",
                        url: "/backend/magazine-image.php?id=" + document.getElementById('magazine-add-photo-id').value,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var img = $(this).find('img').text();
                                        if (status == 'OK') {
                                                var quotehtml = '<div class="magazine-image-big"><a href="https://1x.com/photo/' + document.getElementById('magazine-add-photo-id').value + '" target="_blank"><img src="' + img + '"></a></div>';
                                                tinymce.get('magazine-editor').execCommand('mceInsertContent', false, quotehtml);
                                                closeModal();
                                        } else { alert(status); }
                                });
                        }
                });
        } else {
                alert('Enter an image ID');
        }
}

function hcCurNext() {
        if (document.getElementById('hc_next') != null) {
                hcNext();
        } else {
                setTimeout('hcCurNext2();', 1000);
                nloader('');
        }
}

function hcCurNext2() {
        nloaderstop();
        if (document.getElementById('hc_next') != null) {
                hcNext();
        } else {
                closeModal();
        }
}

function hcNext() {
        if (document.getElementById('hc_next') != null) {
                if (document.getElementById('hc_next').value != '') {
                        modal('headcuration:' + document.getElementById('hc_next').value + ':' + document.getElementById('hc_mode').value);
                        $('#hc_targets').html('');
                }
        }
}

function hcPrev() {
        if (document.getElementById('hc_prev') != null) {
                if (document.getElementById('hc_prev').value != '') {
                        modal('headcuration:' + document.getElementById('hc_prev').value + ':' + document.getElementById('hc_mode').value);
                        $('#hc_targets').html('');
                }
        }
}

function hcCloseShowPhotos(id) {
        if (document.getElementById('hc_interface_image_' + id) != null) {
                $('#hc_interface_image_' + id).css("display", "block");
                $('#hc_interface_showall_' + id).css("display", "none");
                // MOBILE
                $('#headcuration-interface-imagearea-mobile').removeClass("headcuration-interface-imagearea-mobile-hide");
                $('#headcuration-modal-panel').removeClass("headcuration-modal-panel-mobile");
                $('#headcuration-interface-imagearea').removeClass("headcuration-interface-imagearea-mobile");
                hcshowallphotos = 0;
        }
}

function hcShowPhotos(id, user_id) {
        if (document.getElementById('hc_interface_image_' + id) != null) {
                // MOBILE
                $('#headcuration-interface-imagearea-mobile').addClass("headcuration-interface-imagearea-mobile-hide");
                $('#headcuration-modal-panel').addClass("headcuration-modal-panel-mobile");
                $('#headcuration-interface-imagearea').addClass("headcuration-interface-imagearea-mobile");
                // COMPUTER
                $('#hc_interface_image_' + id).css("display", "none");
                $('#hc_interface_showall_' + id).css("display", "block");
                $('#hc_interface_showall_' + id).html('<center><div class="lds-ring"><div></div><div></div><div></div><div></div></div></center>');
                hcshowallphotos = id;
                $.ajax({
                        type: "GET",
                        url: "/backend/hcall.php?id=" + user_id + "&pic_id=" + id,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var data = $(this).find('data').text();
                                        if (status == 'OK') {
                                                $('#hc_interface_showall_' + id).html(data);
                                        } else { alert(status); }
                                });
                        }
                });
        }
}

function hcStatistics() {
        $.ajax({
                type: "GET",
                url: "/backend/hcstatistics.php",
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var data = $(this).find('curatorstats').text();
                                var queue_main = $(this).find('queue_main').text();
                                var queue_dedicated = $(this).find('queue_dedicated').text();
                                var queue_new = $(this).find('queue_new').text();
                                var queue_publishqueue = $(this).find('queue_publishqueue').text();
                                var queue_locked = $(this).find('queue_locked').text();
                                if (status == 'OK') {
                                        if (document.getElementById('headcuration-statistics') != null) {
                                                $('#headcuration-statistics').html(data);
                                        }
                                        if (parseInt(queue_main) > 0) {
                                                $('#queue_main').html(queue_main);
                                                $('#queue_main').fadeIn();
                                        } else {
                                                $('#queue_main').fadeOut();
                                        }
                                        if (parseInt(queue_locked) > 0) {
                                                $('#queue_locked').html(queue_locked);
                                                $('#queue_locked').fadeIn();
                                        } else {
                                                $('#queue_locked').fadeOut();
                                        }
                                        if (document.getElementById('queue_dedicated') != null) {
                                                if (parseInt(queue_dedicated) > 0) {
                                                        $('#queue_dedicated').html(queue_dedicated);
                                                        $('#queue_dedicated').fadeIn();
                                                } else {
                                                        $('#queue_dedicated').fadeOut();
                                                }
                                                if (parseInt(queue_new) > 0) {
                                                        $('#queue_new').html(queue_new);
                                                        $('#queue_new').fadeIn();
                                                } else {
                                                        $('#queue_new').fadeOut();
                                                }
                                        }
                                        if (parseInt(queue_publishqueue) > 0) {
                                                $('#queue_publishqueue').html(queue_publishqueue);
                                                $('#queue_publishqueue').fadeIn();
                                        } else {
                                                $('#queue_publishqueue').fadeOut();
                                        }
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function taggingSave() {
        var phase_id = document.getElementById('phase_id').value;
        var photo_id = document.getElementById('photo_id').value;
        var data_ok = 0;

        if (phase_id == '7' || phase_id == '14' || phase_id == '2') {
                var tags = document.getElementById('tagging-tags').value;
                var data = { id: photo_id, phase: phase_id, tags: tags };
                data_ok = 1;
        }
        if (phase_id == '12') {
                var grade = 0;
                if (document.getElementById('mgrade_1').checked == 1) { grade = '1'; }
                if (document.getElementById('mgrade_2').checked == 1) { grade = '2'; }
                if (document.getElementById('mgrade_3').checked == 1) { grade = '3'; }
                var data = { id: photo_id, phase: phase_id, grade: grade };
                data_ok = 1;
        }
        if (phase_id == '4') {
                var grade = 0;
                if (document.getElementById('grade_1').checked == 1) { grade = '1'; }
                if (document.getElementById('grade_2').checked == 1) { grade = '2'; }
                if (document.getElementById('grade_3').checked == 1) { grade = '3'; }
                if (document.getElementById('grade_4').checked == 1) { grade = '4'; }
                if (document.getElementById('grade_5').checked == 1) { grade = '5'; }
                if (document.getElementById('grade_6').checked == 1) { grade = '6'; }
                var data = { id: photo_id, phase: phase_id, grade: grade };
                data_ok = 1;
        }
        if (phase_id == '3') {
                var people = '0';
                var animals = '0';
                var buildings = '0';
                var inside = '0';
                var modelrelease = '0';
                var badprint = '0';

                if (document.getElementById('people_0').checked) { people = '0'; }
                if (document.getElementById('people_1').checked) { people = '1'; }
                if (document.getElementById('people_2').checked) { people = '2'; }

                if (document.getElementById('animals_0').checked) { animals = '0'; }
                if (document.getElementById('animals_1').checked) { animals = '1'; }
                if (document.getElementById('animals_2').checked) { animals = '2'; }
                if (document.getElementById('animals_3').checked) { animals = '3'; }

                if (document.getElementById('buildings_0').checked) { buildings = '0'; }
                if (document.getElementById('buildings_1').checked) { buildings = '1'; }
                if (document.getElementById('buildings_2').checked) { buildings = '2'; }
                if (document.getElementById('buildings_3').checked) { buildings = '3'; }

                if (document.getElementById('requires_model_release_0').checked) { modelrelease = '0'; }
                if (document.getElementById('requires_model_release_1').checked) { modelrelease = '1'; }

                if (document.getElementById('inside_0').checked) { inside = '0'; }
                if (document.getElementById('inside_1').checked) { inside = '1'; }
                if (document.getElementById('inside_2').checked) { inside = '2'; }

                if (document.getElementById('bad_as_print_0').checked) { badprint = '0'; }
                if (document.getElementById('bad_as_print_1').checked) { badprint = '1'; }

                var data = { id: photo_id, phase: phase_id, people: people, animals: animals, buildings: buildings, modelrelease: modelrelease, inside: inside, badprint: badprint };
                data_ok = 1;
        }
        if (data_ok == 1) {
                $.ajax({
                        type: "POST",
                        url: "/backend/tagging_save.php",
                        data: data,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                if (parseInt(document.getElementById('tagging_' + phase_id).innerHTML) > 0) {
                                                        var remaining = parseInt(document.getElementById('tagging_' + phase_id).innerHTML) - 1;
                                                        document.getElementById('tagging_' + phase_id).innerHTML = remaining;
                                                }
                                                tagging_undo_modal = modalopen;
                                                tagging_undo_picid = photo_id;
                                                tagging_undo_phaseid = phase_id;
                                                modal(modalopen);
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}

function exhibcommentreply(id) {
        document.getElementById('exhib_reply_to').value = id;
        $('#writecomment-status').html('Replying to a comment by ' + document.getElementById('name-' + id).value + ' &nbsp; <span class="button grey xsmall" onclick="abortexhibcommentreply();">Abort</span>');
        $('#writecomment-exhibition').focus();
}

function abortexhibcommentreply() {
        document.getElementById('exhib_reply_to').value = '';
        $('#writecomment-status').html('');
}


function writeCommentExhibition(id) {
        var reply_to = 0;
        if (parseInt(document.getElementById('exhib_reply_to').value) > 0) {
                reply_to = document.getElementById('exhib_reply_to').value;
        }
        if (document.getElementById('writecomment-exhibition').value != '') {
                $('#writecomment-exhibition-btn').css("opacity", "0.4");
                $.ajax({
                        type: "POST",
                        url: "/backend/writecommentexhibition.php",
                        data: { id: id, reply: reply_to, msg: document.getElementById('writecomment-exhibition').value },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                document.getElementById('writecomment-exhibition').value = '';
                                                getexhibitioncomments(id);
                                                $('#writecomment-exhibition-btn').css("opacity", "1");
                                                abortexhibcommentreply();
                                                if (reply_to == 0) {
                                                }
                                        } else {
                                                alert(status);
                                                $('#writecomment-exhibition-btn').css("opacity", "1");
                                        }
                                });
                        }
                });
        } else {
                alert('No comment written');
        }
}

function taggingUndo() {
        if (tagging_undo_modal && tagging_undo_picid && tagging_undo_phaseid) {
                $.ajax({
                        type: "GET",
                        url: "/backend/tagging_undo.php?id=" + tagging_undo_picid + "&phase=" + tagging_undo_phaseid,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                tagging_undo_picid = '';
                                                tagging_undo_phaseid = '';
                                                modal(tagging_undo_modal);
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}

function hcDisc(id) {
        var curdiscmsg = document.getElementById('curdisc_' + id).value;
        document.getElementById('curdisc_' + id).value = '';
        if (curdiscmsg != '') {
                blockarrows = 0;
                document.getElementById('curdisc_' + id).style.opacity = '0.3';
                $('#curdisc_button_' + id).css("opacity", "0.3");
                $.ajax({
                        type: "POST",
                        url: "/backend/hcdisc.php",
                        data: { id: id, msg: curdiscmsg },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                hcStats(id);
                                        } else { alert(status); }
                                });
                        }
                });

        }
}

function signupnewsletter() {
        if (document.getElementById('signup_newsletter').value != '') {
                $.ajax({
                        type: "POST",
                        url: "/backend/newsletter.php",
                        data: { email: document.getElementById('signup_newsletter').value },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                $('#newsletter_target').html('<div class="subheader">You are now signed up. Thanks!</div>');
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}

function deleteMagazine(id) {
        var agree = confirm('Are you sure you want to delete this article?');
        if (agree) {
                $.ajax({
                        type: "POST",
                        url: "/backend/deletemagazine.php",
                        data: { id: id },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                location.href = '/magazine/archive';
                                        } else { alert(status); }
                                });
                        }
                });
        }
}

function saveMagazine() {
        var magazine_id = document.getElementById('magazine_id').value;
        var magazine_text = tinymce.get("magazine-editor").getContent();
        var magazine_header = document.getElementById('magazine-header').value;
        if (magazine_text) {
                if (magazine_header) {
                        if (document.getElementById('magazine-published').checked == 1) {
                                var magazine_publish = 1;
                        } else {
                                var magazine_publish = 0;
                        }
                        $.ajax({
                                type: "POST",
                                url: "/backend/savemagazine.php",
                                data: { id: magazine_id, mag_text: magazine_text, header: magazine_header, publish: magazine_publish },
                                dataType: "xml",
                                success: function (xml) {
                                        $(xml).find('root').each(function () {
                                                var status = $(this).find('status').text();
                                                var url = $(this).find('url').text();
                                                if (status == 'OK') {
                                                        if (magazine_id) {
                                                                centermessage('Article saved', 2000);
                                                        } else {
                                                                location.href = '/magazine/permalink/' + url + '/edit';
                                                        }
                                                } else {
                                                        alert(status);
                                                }
                                        });
                                }
                        });
                } else {
                        alert('Article must have a title');
                }
        } else {
                alert('Article must contain text');
        }
}

function directorySetTitle(id, title) {
        if (document.getElementById('directory-title-' + id) != null) {
                $('#directory-title-' + id).html('<input type="text" class="directory-input-text" placeholder="Image title" onblur="directorySaveTitle(\'' + id + '\');" onkeydown="if(event.keyCode==13) { directorySaveTitle(\'' + id + '\'); }" value="' + title + '" id="directory-title-edit-' + id + '"> <span class="button small jade">Save</span>');
                $('#directory-title-edit-' + id).focus();
                $('#directory-status-mobile-' + id).addClass("directory-status-mobile-hidden");
        }
}

function directorySaveTitle(id) {
        var newtitle = document.getElementById('directory-title-edit-' + id).value;

        $.ajax({
                type: "POST",
                url: "/backend/directory_savetitle.php",
                data: { id: id, title: newtitle },
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        if (newtitle == '') {
                                                var titlehtml = '<div onclick="directorySetTitle(\'' + id + '\',\'\');" style="cursor: pointer; color: var(--curatered);"><span>Untitled</span><span style=\"font-size: 0.8em; font-weight: 500; opacity: .5; font-style: italic;\"> - Click here to set title</span></div>';
                                        } else {
                                                var newtitle2 = newtitle.replace(/'/g, "\\'");
                                                var titlehtml = '<div onclick="directorySetTitle(\'' + id + '\',\'' + newtitle2 + '\');" style="cursor: pointer;">' + newtitle + ' <span class="directory-title-edit"><i class="fas fa-edit"></i></span></div>';
                                        }

                                        $('#directory-title-' + id).html(titlehtml);
                                        $('#directory-status-mobile-' + id).removeClass("directory-status-mobile-hidden");
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function directorySaveCategory(id, cat_id) {
        $.ajax({
                type: "GET",
                url: "/backend/directory_savecategory.php?id=" + id + "&cat_id=" + cat_id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        directoryRefresh(id, 'directory-' + id);
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function changeCategory(id, cat_id) {
        $.ajax({
                type: "GET",
                url: "/backend/changecategory.php?id=" + id + "&cat_id=" + cat_id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        $('#categorychanged_' + id).html('Changed!');
                                        setTimeout('$(\'#categorychanged_' + id + '\').html(\'\');', 1000);
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function hcStatsT(id) {
        clearTimeout(hcstatstimer);
        hcstatstimer = setTimeout('hcStats(\'' + id + '\');', 100);
}

function hcStats(id) {
        if (document.getElementById('hc_curstats_' + id) != null) {
                $.ajax({
                        type: "GET",
                        url: "/backend/hcstats.php?id=" + id + "&mode=" + document.getElementById('hc_mode').value,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var hc_curstats = $(this).find('hc_curstats').text();
                                        var hc_discussion = $(this).find('hc_discussion').text();
                                        var hc_about = $(this).find('hc_about').text();
                                        var reject = $(this).find('reject').text();
                                        var week = $(this).find('week').text();
                                        if (status == 'OK') {
                                                $('#hc_curstats_' + id).html(hc_curstats);
                                                $('#hc_discussion_' + id).html(hc_discussion);
                                                $('#hc_about_' + id).html(hc_about);
                                                if (reject == '0') {
                                                        $('#rejectbutton_' + id).css("opacity", "0.3");
                                                } else {
                                                        $('#rejectbutton_' + id).css("opacity", "1");
                                                        if (document.getElementById('hc_noreject') != null) {
                                                                document.getElementById('hc_noreject').value = '0';
                                                        }
                                                }
                                                if (parseInt(week) > 1000) {
                                                        document.getElementById('hc_nodecision').value = '1';
                                                } else {
                                                        document.getElementById('hc_nodecision').value = '0';
                                                }
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}

function taggingTagProcess() {
        var addtag = document.getElementById('tagging-addtag').value;
        addtag = addtag.toUpperCase();
        if (document.getElementById('tagging-addtag').value != addtag) {
                document.getElementById('tagging-addtag').value = addtag;
        }
}

function taggingAddTag() {
        var addtag = document.getElementById('tagging-addtag').value;
        addtag = addtag.toUpperCase();
        if (addtag != '') {
                var blockadd = 0;
                $('#tagging-current').children().each(function () {
                        if (this.innerHTML == addtag) { blockadd = 1; }
                });
                if (blockadd == 0) {
                        document.getElementById('tagging-addtag').value = '';
                        //blockenter=1;
                        //clearTimeout(blockentertimer);
                        //blockentertimer = setTimeout('blockenter=0;',500);
                        $('#tagging-current').append('<span onclick="$(this).remove(); taggingProcessTags();" class="headcuration-modal-panel-info-text-tag">' + addtag + '</span> ');
                        taggingProcessTags();
                } else {
                        //blockenter=1;
                        //clearTimeout(blockentertimer);
                        //blockentertimer = setTimeout('blockenter=0;',500);
                        document.getElementById('tagging-addtag').value = '';

                }
        }
        document.getElementById('tagging-addtag').focus();
}

function taggingAddTagForce(addtag) {
        addtag = addtag.toUpperCase();
        if (addtag != '') {
                var blockadd = 0;
                $('#tagging-current').children().each(function () {
                        if (this.innerHTML == addtag) { blockadd = 1; }
                });
                if (blockadd == 0) {
                        document.getElementById('tagging-addtag').value = '';
                        $('#tagging-current').append('<span onclick="$(this).remove(); taggingProcessTags();" class="headcuration-modal-panel-info-text-tag">' + addtag + '</span> ');
                        taggingProcessTags();
                }
        }
        document.getElementById('tagging-addtag').focus();
}

function taggingProcessTags() {
        var alltags = '';
        $('#tagging-current').children().each(function () {
                if (alltags != '') { alltags += ','; }
                alltags += this.innerHTML;
        });
        document.getElementById('tagging-tags').value = alltags;
}

function hcPrevNext(id) {
        var godynamic = 0;

        if (document.getElementById('hc_' + id) != null) {

                var foundprev = 0;
                var foundnext = 0;
                var hasfound = 0;
                var prevcache = '';

                $('#photos-feed').children().each(function () {
                        var img_id = this.id;
                        img_id = img_id.replace("hc_", "");
                        if (parseInt(img_id) > 0) {
                                if (hasfound && foundnext == 0) {
                                        foundnext = img_id;
                                }
                                if (img_id == id) {
                                        foundprev = prevcache;
                                        hasfound = 1;
                                }
                                prevcache = img_id;
                        }
                });

                var fdata = '';
                if (parseInt(foundnext) > 0) {
                        fdata += '<input type="hidden" id="hc_next" value="' + foundnext + '">';
                        $('#hc_next_icon').css("opacity", "1");
                }
                if (parseInt(foundprev) > 0) {
                        fdata += '<input type="hidden" id="hc_prev" value="' + foundprev + '">';
                        $('#hc_prev_icon').css("opacity", "1");
                }
                if (fdata != '') {
                        $('#hc_targets').html(fdata);
                } else {
                        godynamic = 1;
                }

        } else {
                godynamic = 1;
                doLoadmore();
        }

        if (godynamic == 1) {

                if (document.getElementById('hc_curstats_' + id) != null) {
                        $.ajax({
                                type: "GET",
                                url: "/backend/hcprevnext.php?id=" + id + "&mode=" + document.getElementById('hc_mode').value,
                                dataType: "xml",
                                success: function (xml) {
                                        $(xml).find('root').each(function () {
                                                var status = $(this).find('status').text();
                                                var data = $(this).find('data').text();
                                                var prev = $(this).find('prev').text();
                                                var next = $(this).find('next').text();
                                                if (status == 'OK') {
                                                        $('#hc_targets').html(data);
                                                        if (parseInt(prev) > 0) {
                                                                $('#hc_prev_icon').css("opacity", "1");
                                                        }
                                                        if (parseInt(next) > 0) {
                                                                $('#hc_next_icon').css("opacity", "1");
                                                        }
                                                } else {
                                                        alert(status);
                                                }
                                        });
                                }
                        });
                }

        }
}

function savePurpose() {
        $('#savepurpose').css("opacity", "0.3");
        if (document.getElementById('purp_exposure') != null) {
                if (document.getElementById('purp_exposure').value == '1' || document.getElementById('purp_sell').value == '1' || document.getElementById('purp_learn').value == '1' || document.getElementById('purp_look').value == '1' || document.getElementById('purp_inspire').value == '1') {
                        $.ajax({
                                type: "GET",
                                url: "/backend/savepurp.php?purp_exposure=" + document.getElementById('purp_exposure').value + "&purp_sell=" + document.getElementById('purp_sell').value + "&purp_learn=" + document.getElementById('purp_learn').value + "&purp_look=" + document.getElementById('purp_look').value + "&purp_inspire=" + document.getElementById('purp_inspire').value,
                                dataType: "xml",
                                success: function (xml) {
                                        $(xml).find('root').each(function () {
                                                var status = $(this).find('status').text();
                                                var next = $(this).find('next').text();
                                                if (status == 'OK') {
                                                        $('#savepurpose').css("opacity", "1");
                                                        if (next == '1') {
                                                                modal('guide');
                                                        } else {
                                                                closeModal();
                                                        }
                                                } else { alert(status); $('#savepurpose').css("opacity", "1"); }
                                        });
                                }
                        });
                } else {
                        alert('You must select at least one of the options. Click it to select it.');
                }
        }
}

function reuploadmodal(id) {
        closeModal(); setTimeout('modal(\'reupload:' + id + ':\',\'\',\'\');', 700);
}

function selectExhibCover(id) {
        if (parseInt(document.getElementById('feat_exhib_img').value) > 0) {
                $('#exhibimg-' + document.getElementById('feat_exhib_img').value).css("padding", "3px");
                $('#exhibimg-' + document.getElementById('feat_exhib_img').value).css("border", "0px");
        }
        $('#exhibimg-' + id).css("padding", "0px");
        $('#exhibimg-' + id).css("border", "3px solid var(--jade)");
        document.getElementById('feat_exhib_img').value = id;
}

function blockRightClick(event) {
        if (event.button == 2) {
                alert('This photo is copyrighted');
                return false;
        }
}

function blockDownload() {
        return false;
}

function reportHandle(id, action) {
        $.ajax({
                type: "GET",
                url: "/backend/report_handle.php?id=" + id + "&a=" + action,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        $('#report-' + id).fadeOut();
                                } else { alert(status); }
                        });
                }
        });
}

function doReport(id) {

        $('#reportbutton').css("opacity", "0.3");

        $.ajax({
                type: "GET",
                url: "/backend/report.php?id=" + id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        closeModal();
                                        getCurate();
                                } else { $('#reportbutton').css("opacity", "1"); alert(status); }
                        });
                }
        });
}

function notificationsShow() {
        $('#notifications-back').css("display", "block");
        $('#notifications-front').css("display", "block");
        $('#notifications-front').animate({ right: "0px" }, 300);
        $('#notifications-front').html('<table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%"><tr><td><center><div class="lds-ring"><div></div><div></div><div></div><div></div></div></center></td></tr></table>');
        bodystopscroll();

        $.ajax({
                type: "GET",
                url: "/backend/notif.php",
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var data = $(this).find('data').text();
                                if (status == 'OK') {
                                        $('#notifications-front').html(data);
                                        $('#notifications-front-notif').fadeIn();
                                        $('#rightbubble-notification').removeClass("rightbubble-on");
                                        $('#rightbubble-notification2').removeClass("rightbubble-on");
                                        document.title = basetitle;
                                        mixpanel.track('Opened notifications');
                                }
                        });
                }
        });


}

function accountadmin(action) {
        var actiona = action.split(":");

        $.ajax({
                type: "GET",
                url: "/backend/accountadmin.php?action=" + action,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        if (actiona[0] == 'delete') {
                                                if (document.getElementById('actions-delete') == null) {
                                                        $('#id_' + actiona[1]).fadeOut();
                                                } else {
                                                        location.href = '/';
                                                }
                                        }
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function starttrial() {
        $('#trial01').css("opacity", "0.3");
        $('#trial02').css("opacity", "0.3");
        nloader('Enabling PRO...');
        $.ajax({
                type: "GET",
                url: "/backend/starttrial.php",
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        setTimeout('location.href=\'/pro/enabled\';', 2000);
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function starttrial2() {
        $('#starttrial').css("opacity", "0.3");
        $.ajax({
                type: "GET",
                url: "/backend/starttrial.php",
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        $('#guide_01').fadeOut();
                                        setTimeout('confetti.start();', 700);
                                        setTimeout('confetti.stop();', 5000);
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function notificationsHide() {
        $('#notifications-back').css("display", "none");
        $('#notifications-front').css("display", "none");
        bodyscroll();
}

function featureexhib(publish) {
        if (parseInt(document.getElementById('feat_exhib_img').value) > 0 && document.getElementById('feat_exhib_title').value != '' && document.getElementById('feat_exhib_desc').value != '') {

                var exhib_start = document.getElementById('feat_exhib_start').value;
                var exhib_stop = document.getElementById('feat_exhib_stop').value;
                $.ajax({
                        type: "POST",
                        url: "/backend/featureexhib.php",
                        data: { id: document.getElementById('feat_exhib_id').value, title: document.getElementById('feat_exhib_title').value, text: document.getElementById('feat_exhib_desc').value, img: document.getElementById('feat_exhib_img').value, publish: publish, start: exhib_start, stop: exhib_stop },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                if (publish == '1') {
                                                        $('#featureinfo').html('<div style="color: green; padding: 20px; text-align: center;">Feature saved and published</div>');
                                                } else {
                                                        $('#featureinfo').html('<div style="color: green; padding: 20px; text-align: center;">Feature saved</div>');
                                                }
                                        } else { alert(status); }
                                });
                        }
                });
        } else {
                alert('Make sure all fields are filled in and a image is selected');
        }
}

function deleteBlogComment(id) {
        var agree = confirm('Are you sure?');
        if (agree) {
                $.ajax({
                        type: "GET",
                        url: "/backend/deleteblogcomment.php?id=" + id,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                $('#blogcomment_' + id).remove();
                                        }
                                });
                        }
                });
        }
}

function followf(user_id) {
        $(".followbuttons-" + user_id).each(function (index) {
                var elementid = $(this).attr("id");
                if (elementid != '') {
                        $('#' + elementid).css("opacity", "0.3");
                }
        });

        $.ajax({
                type: "GET",
                url: "/backend/follow.php?id=" + user_id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var label = $(this).find('label').text();
                                if (status == 'OK') {
                                        $(".followbuttons-" + user_id).each(function (index) {
                                                var elementid = $(this).attr("id");
                                                if (elementid != '') {
                                                        $('#' + elementid).css("opacity", "1");
                                                        $('#' + elementid).html(label);
                                                }
                                        });

                                }
                        });
                }
        });
}


function followp(user_id, pic_id) {
        $('#followbutton-' + pic_id).css("opacity", "0.3");

        $.ajax({
                type: "GET",
                url: "/backend/follow.php?id=" + user_id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var label = $(this).find('label').text();
                                if (status == 'OK') {
                                        $('#followbutton-' + pic_id).css("opacity", "1");
                                        $('#followbutton-' + pic_id).html(label);
                                }
                        });
                }
        });

}

function follow(user_id) {
        $('#follow1').css("opacity", "0.3");
        $('#follow2').css("opacity", "0.3");
        $.ajax({
                type: "GET",
                url: "/backend/follow.php?id=" + user_id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var label = $(this).find('label').text();
                                if (status == 'OK') {
                                        $('#follow1').css("opacity", "1");
                                        $('#follow2').css("opacity", "1");
                                        $('#follow1').html(label);
                                        $('#follow2').html(label);
                                }
                        });
                }
        });
}

function followmodal(user_id) {
        $.ajax({
                type: "GET",
                url: "/backend/follow.php?id=" + user_id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var label = $(this).find('label').text();
                                if (status == 'OK') {
                                        if (label == 'Follow') {
                                                $('#followtarget-' + user_id).html('<span onclick="followmodal(\'' + user_id + '\');" class="button medium blue">Follow</span>');
                                        } else {
                                                $('#followtarget-' + user_id).html('<span onclick="followmodal(\'' + user_id + '\');" class="button medium grey">Unfollow</span>');
                                        }
                                }
                        });
                }
        });
}


function singlePhotoPrev() {
        if (parseInt(store_prevnext_prev) > 0) {
                var current_location = window.location.pathname;
                var ida = current_location.split("/");

                location.href = '/' + ida[1] + '/' + store_prevnext_prev + '/' + ida[3];
        }
}

function singlePhotoNext() {
        if (parseInt(store_prevnext_next) > 0) {
                var current_location = window.location.pathname;
                var ida = current_location.split("/");

                location.href = '/' + ida[1] + '/' + store_prevnext_next + '/' + ida[3];
        }
}

$(window).scroll(function () {
        scroller('0');
});

$(window).on('popstate', function () {
        urlCheck();
});

function nloader(msg) {
        $('#newloader').css("display", "block");
        $('#newloader-message').html(msg);
}

function nloaderstop() {
        $('#newloader').css("display", "none");
        $('#newloader-message').html('');
}

function nloadermsg(msg) {
        $('#newloader-message').html(msg);
}

function forumtag() {
        var inserttag = document.getElementById('tag-input').value;
        inserttag = inserttag.toUpperCase();
        inserttag = inserttag.replace(' ', '_');
        inserttag = inserttag.replace(/\W/g, '');
        inserttag = inserttag.replace('_', ' ');
        if (inserttag.length > 2 && document.getElementById('tag_' + inserttag) == null) {
                if (document.getElementById('forum-notags') != null) { $('#forum-notags').remove(); }
                document.getElementById('tag-input').value = '';
                $('#forum-tags').append('<span id="tag_' + inserttag + '" class="forum-newtopic-tag"><span onclick="removeforumtag(\'' + inserttag + '\');" class="forum-thread-tag"><span class="forum-topics-tagsign">#</span>' + inserttag + '</span> </span>');
        }
        updateforumtags();
}

function removeforumtag(tag) {
        if (document.getElementById('tag_' + tag) != null) {
                $('#tag_' + tag).remove();
                if (document.getElementById('forum-tags').innerHTML == '') {
                        $('#forum-tags').html('<span id="forum-notags" class="forum-currenttags-notags">No tags added</span>');
                }
        }
        updateforumtags();
}

function updateforumtags() {
        var alltags = '';
        $(".forum-newtopic-tag").each(function (index) {
                var elementid = $(this).attr("id");
                if (elementid != '') {
                        elementid = elementid.replace('tag_', '');
                        if (alltags != '') { alltags += ','; }
                        alltags += elementid;
                }
        });
        document.getElementById('forum-newtopic-tags').value = alltags;
}

function singlePhotoNextPrev() {

        store_prevnext_next = 0;
        store_prevnext_prev = 0;

        var current_location = window.location.pathname;

        $.ajax({
                type: "GET",
                url: me + "/backend/nextprev.php?id=" + current_location,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var nextprev_prev = $(this).find('nextprev_prev').text();
                                var nextprev_next = $(this).find('nextprev_next').text();
                                if (status == 'OK') {
                                        if (parseInt(nextprev_prev) > 0) {
                                                $('#single-photo-navigation-prev').css("display", "block");
                                                $('#single-photo-navigation-prev').addClass("single-photo-navigation-peak");
                                                store_prevnext_prev = nextprev_prev;
                                        } else {
                                                $('#single-photo-navigation-prev').css("display", "none");
                                        }
                                        if (parseInt(nextprev_next) > 0) {
                                                $('#single-photo-navigation-next').css("display", "block");
                                                $('#single-photo-navigation-next').addClass("single-photo-navigation-peak");
                                                store_prevnext_next = nextprev_next;
                                        } else {
                                                $('#single-photo-navigation-next').css("display", "none");
                                        }
                                        clearTimeout(prevnexttimer);
                                        prevnexttimer = setTimeout('singlePhotoNextPrevHide();', 2000);
                                } else {
                                        $('#single-photo-navigation-next').css("display", "none");
                                        $('#single-photo-navigation-prev').css("display", "none");
                                }
                        });
                }
        });
}

function singlePhotoNextPrevHide() {
        //$('#single-photo-navigation-prev').animate({ opacity: "0" }, 1500);
        $('#single-photo-navigation-prev').removeClass("single-photo-navigation-peak");
        $('#single-photo-navigation-next').removeClass("single-photo-navigation-peak");
        //$('#single-photo-navigation-prev').css("opacity","unset");
}

function reuploadscr(id, action) {
        $.ajax({
                type: "GET",
                url: "/backend/reuploadscreening.php?id=" + id + "&action=" + action,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        $('#reupload-' + id).remove();
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function saveMethod(code) {
        var payout_method = 0;
        if (document.getElementById('method_2').checked == 1) { payout_method = 2; }
        if (document.getElementById('method_3').checked == 1) { payout_method = 3; }
        if (document.getElementById('method_4') != null) { if (document.getElementById('method_4').checked == 1) { payout_method = 4; } }
        if (payout_method > 0) {
                if (savingmethod == 0) {
                        savingmethod = 1;
                        document.getElementById('savemethodbutton').style.opacity = '0.3';
                        document.getElementById('savemethodbuttonb').innerHTML = 'Please wait';

                        $.ajax({
                                type: "GET",
                                url: "/backend/savemethod.php?method=" + payout_method + "&code=" + code,
                                dataType: "xml",
                                success: function (xml) {
                                        $(xml).find('root').each(function () {
                                                var status = $(this).find('status').text();
                                                if (status == 'OK') {
                                                        location.href = '/royalty/' + code + '/success';
                                                } else {
                                                        alert(status);
                                                        document.getElementById('savemethodbutton').style.opacity = '1';
                                                        document.getElementById('savemethodbuttonb').innerHTML = 'Save';
                                                        savingmethod = 0;
                                                }
                                        });
                                }
                        });
                }
        }
}



function checkMethod() {
        var checkok = 0;

        if (document.getElementById('method_2').checked == 1 || document.getElementById('method_3').checked == 1) {
                checkok = 1;
        }

        if (document.getElementById('method_4') != null) { if (document.getElementById('method_4').checked == 1) { checkok = 1; } }

        if (checkok == 1) {
                document.getElementById('savemethodbutton').style.opacity = '1';
        } else {
                document.getElementById('savemethodbutton').style.opacity = '0.3';
        }
}

function commentReply(id, pic_id) {
        $('#photo-detail-comment-replybutton-' + id).css("display", "none");
        $('#photo-detail-comment-replygui-' + id).html('<div class="photo-detail-writecomment-reply"><textarea class="photo-detail-writecomment" id="comment-reply-' + id + '" onkeyup="if(this.value != \'\') { $(\'#reply-button-' + id + '\').css(\'opacity\',\'1\'); } else { $(\'#reply-button-' + id + '\').css(\'opacity\',\'0.4\'); }" placeholder="Write a reply"></textarea></div><div class="photo-detail-writecomment-button"><span class="button jade small" style="opacity: .4;" id="reply-button-' + id + '" onclick="commentReplyDo(\'' + id + '\',\'' + pic_id + '\');">Reply</span></div><img src="https://gamma.1x.com/assets/img/1x-logo-2.png" style="display: none;" onload="autosize($(\'#comment-reply-' + id + '\'));">');
        $('#comment-reply-' + id).focus();
}

function messengerHeight() {
        if (document.getElementById('messenger-back') == null) {
                var totalheight = parseInt($('#modal-messenger-ui-right').height()) - 20;
                var reduceheight = $('#modal-messenger-ui-write').height();
                $('#modal-messenger-ui-message').css("max-height", totalheight - reduceheight + 'px');
                messengerScroll('1');
        } else {
                var totalheight = parseInt($('#modal-messenger-ui-right').height()) - 220;
                $('#modal-messenger-ui-message').css("max-height", totalheight + 'px');
                messengerScroll('1');
        }
}

var runningaction = '';

function runaction(action, id, text, button, extra, extra2) {
        if (runningaction == '') {
                runningaction = action;
                if (button) {
                        if (document.getElementById(button) != null) {
                                document.getElementById(button).style.opacity = '0.3';
                        }
                }


                $.ajax({
                        type: "POST",
                        url: "/backend/runaction.php",
                        data: { action: action, id: id, text: text, extra: extra, extra2: extra2, button: button },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var action = $(this).find('action').text();
                                        var id = $(this).find('id').text();
                                        var button = $(this).find('button').text();
                                        var extra = $(this).find('extra').text();
                                        var extra2 = $(this).find('extra2').text();
                                        if (status == 'OK') {
                                                if (action == 'marktransactionsaspaid') {
                                                        location.href = location.href;
                                                }
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}

function quickReply(pic_id, comment_id, not_id) {
        $('#quickreply-div-' + comment_id).css("opacity", "0.3");
        var comment = document.getElementById('quickreply-' + comment_id).value;
        $.ajax({
                type: "POST",
                url: "/backend/writecomment.php",
                data: { id: pic_id, comment: comment, reply: comment_id, not_id: not_id },
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        $('#quickreply-div-' + comment_id).css("opacity", "1");
                                        $('#quickreply-div-' + comment_id).html('<div class="notif-textdata-reply-icon"><i class="fas fa-check-circle"></i></div><div class="notif-textdata-reply-text">You replied to this comment</div>');
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function commentReplyDo(id, pic_id) {
        if (document.getElementById('comment-reply-' + id).value != '') {
                var comment = document.getElementById('comment-reply-' + id).value;

                $.ajax({
                        type: "POST",
                        url: "/backend/writecomment.php",
                        data: { id: pic_id, comment: comment, reply: id },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                $('#photo-detail-comment-replybutton-' + id).css("display", "block");
                                                $('#photo-detail-comment-replygui-' + id).html('');
                                                $('#photo-detail-replies-' + pic_id + '-' + id).css("display", "block");
                                                var commenthtml = '<div class="photo-detail-comment-reply"><div class="photo-detail-comment-name-reply">' + auth_name;
                                                if (auth_membership == '1') {
                                                        commenthtml += ' <span class="pro-label-small">' + auth_title + '</span>';
                                                }
                                                commenthtml += '</div><div class="photo-detail-comment-text-reply">' + comment + '</div></div>';
                                                $('#photo-detail-replies-' + pic_id + '-' + id).prepend(commenthtml);
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        } else {
                alert('Please write a reply');
        }
}

function invitesetpw(invite_code) {
        var pw1 = document.getElementById('signup_password').value;
        var pw2 = document.getElementById('signup_password2').value;

        if (document.getElementById('signup_email') != null) {
                var signup_email = document.getElementById('signup_email').value;
        } else {
                var signup_email = '';
        }

        if (pw1.length > 7) {
                if (pw1 == pw2) {
                        $.ajax({
                                type: "POST",
                                url: "/backend/invited.php",
                                data: { code: invite_code, pw1: pw1, pw2: pw2, signup_email: signup_email },
                                dataType: "xml",
                                success: function (xml) {
                                        $(xml).find('root').each(function () {
                                                var status = $(this).find('status').text();
                                                if (status == 'OK') {
                                                        location.href = '/';
                                                } else {
                                                        alert(status);
                                                }
                                        });
                                }
                        });

                } else {
                        alert('The repeated password does not match the first entered password');
                }
        } else {
                alert('Password must be at least 8 characters');
        }
}

function saveeditprofile() {
        $.ajax({
                type: "POST",
                url: "/backend/saveeditprofile.php",
                data: { s_location: document.getElementById('s_location').value, s_presentation: document.getElementById('s_presentation').value, s_instagram: document.getElementById('s_instagram').value },
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        mixpanel.track('Saved profile information');
                                        location.href = '/';
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function ambcreateuser2() {
        $('#loader').fadeIn();
        // illustrator_invite
        if (document.getElementById('illustrator_invite') != null) {
                var illustrator = '1';
        } else {
                var illustrator = '0';
        }
        if (document.getElementById('amb_name').value != '') {
                $.ajax({
                        type: "POST",
                        url: "/backend/ambcreateuser2.php",
                        data: { name: document.getElementById('amb_name').value, illustrator: illustrator },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                if (illustrator == '0') {
                                                        location.href = '/ambassador';
                                                } else {
                                                        location.href = '/illustrators';
                                                }
                                        } else {
                                                $('#loader').fadeOut();
                                                alert(status);
                                        }
                                });
                        }
                });
        } else {
                alert('Fill in name/description');
        }
}

function ambcreateuser() {
        $('#loader').fadeIn();
        if (document.getElementById('amb_username').value != '' && document.getElementById('amb_name').value != '') {
                $.ajax({
                        type: "POST",
                        url: "/backend/ambcreateuser.php",
                        data: { username: document.getElementById('amb_username').value, name: document.getElementById('amb_name').value, email: document.getElementById('amb_email').value },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                location.href = '/ambassador';
                                        } else {
                                                $('#loader').fadeOut();
                                                alert(status);
                                        }
                                });
                        }
                });
        } else {
                alert('Fill in all three fields');
        }
}

function disableMsgEditor() {
        $('#btn_msg_send').addClass("disabled");
        $("#btn_msg_send").attr("disabled", true);
        $("#msg_text").attr("disabled", true);
}

function enableMsgEditor() {
        $('#btn_msg_send').removeClass("disabled");
        $("#btn_msg_send").removeAttr("disabled");
        $("#msg_text").removeAttr("disabled");

        if (typeof (window.innerWidth) == 'number') {
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
        }

        if (parseInt(myWidth) > 1149) {
                $('#msg_text').focus();
        }

}



$(window).on('resize', function () {
        if (document.getElementById('messages_reader') != null) {
                var basewidth = parseInt($('#modal-inner-block2').innerWidth()) - 300;
                if (myHeight < myWidth) {
                        $('#messages_reader').css("width", basewidth + "px");
                        $('#messages_editor').css("width", basewidth + "px");
                }
        }
        if (document.getElementById('modal-messenger-ui-message') != null) { messengerHeight(); }
});

function displaymode(what) {
        deleteCookie('DisplayMode');
        deleteCookie('DisplayMode');
        setCookie('DisplayMode', what, '10000');
        location.href = location.href;
}

function deleteCookie(name) {
        document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}


function setCookie(c_name, value, exdays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + exdays);
        var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
        document.cookie = c_name + "=" + c_value;
}

function closePurpose() {
        setCookie('purpose-not-show', '1', '1');
        closeModal();
}

function switchfrontsort(what) {
        if (what == 'pop' || what == 'feed') {
                setCookie('frontmode', what, '10');
                location.href = '/';
        }
}

function urlCheck() {
        var current_location = window.location.pathname;
        var ida = current_location.split("/");
        var actionblock = '';
        if (actionblock == '') {
                if (ida[1] == 'photo' && parseInt(ida[2]) > 0) {
                        openPhoto(ida[2]);
                } else {
                        closeLastOpenedPhoto();
                }
                if (ida[1] == 'headcuration' && parseInt(ida[3]) > 0) {
                        modal('headcuration:' + ida[3] + ':' + ida[2]);
                }
                if (ida[1] == 'headcuration' && !parseInt(ida[3]) > 0) {
                        closeModal();
                }
        }
}


jQuery(function ($) {
        $('#modal').on('scroll', function () {
                if (modalopen == 'overview') {
                        if ($(this).scrollTop() +
                                $(this).innerHeight() >=
                                $(this)[0].scrollHeight) {
                                overviewLoad();
                        }
                }
        });
});


var bubbletimer;

function bubble(x, btime) {
        if (!btime) { btime = 2000; }
        $('#xbubble-container').html('<div id="xbubble" class="xbubble animated zoomIn fast" onclick="bubblehide();"><span class="xbubble-plus">+</span>' + x + '</div>');
        if (document.getElementById('xbubble2-container') != null) {
                $('#xbubble2-container').html('<div id="xbubble2" class="xbubble2 animated zoomIn fast" onclick="bubblehide();"><span class="xbubble2-plus">+</span>' + x + '</div>')
        }
        clearTimeout(bubbletimer);
        bubbletimer = setTimeout('bubblehide();', btime);
}

function bubblehide() {
        $('#xbubble').removeClass("zoomIn");
        $('#xbubble').addClass("zoomOut");
        if (document.getElementById('xbubble2-container') != null) {
                $('#xbubble2').removeClass("zoomIn");
                $('#xbubble2').addClass("zoomOut");
        }
}

function executeTuner() {
        document.getElementById('loader').style.display = 'block';
        document.getElementById('loaderbackdrop').style.display = 'block';

        var e_reject = '';
        var e_publish = '';

        $(".execute_reject").each(function (index) {
                var elementid = $(this).attr("id");
                if (document.getElementById(elementid).checked == 1) {
                        elementid = elementid.replace('status_', '');
                        elementid = elementid.replace('_3', '');
                        if (document.getElementById('img_' + elementid).style.display == 'inline-block') {
                                if (e_reject != '') { e_reject += ','; }
                                e_reject += elementid;
                        }
                }
        });

        $(".execute_publish").each(function (index) {
                var elementid = $(this).attr("id");
                if (document.getElementById(elementid).checked == 1) {
                        elementid = elementid.replace('status_', '');
                        elementid = elementid.replace('_4', '');
                        if (document.getElementById('img_' + elementid).style.display == 'inline-block') {
                                if (e_publish != '') { e_publish += ','; }
                                e_publish += elementid;
                        }
                }
        });

        $.ajax({
                type: "POST",
                url: me + "/backend/execute_tuner.php",
                data: { publish: e_publish, reject: e_reject },
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        document.getElementById('loaderbackdrop').style.display = 'none';
                                        document.getElementById('loader').style.display = 'none';
                                        tunerLoad();
                                } else {
                                        document.getElementById('loaderbackdrop').style.display = 'none';
                                        document.getElementById('loader').style.display = 'none';
                                        alert(status);
                                }
                        });
                }
        });
}

function saveTuner() {
        document.getElementById('loader').style.display = 'block';
        if (parseInt(document.getElementById('tuner_accuracy_weight').value) > 0 && parseInt(document.getElementById('tuner_accuracy_weight').value) < 100) {
                def_tuner_accuracy_weight = document.getElementById('tuner_accuracy_weight').value;
        } else {
                document.getElementById('tuner_accuracy_weight').value = def_tuner_accuracy_weight;
        }

        if (parseInt(document.getElementById('tuner_req_percent').value) > 0 && parseInt(document.getElementById('tuner_req_percent').value) < 100) {
                def_tuner_require_phase_one = document.getElementById('tuner_req_percent').value;
        } else {
                document.getElementById('tuner_req_percent').value = def_tuner_require_phase_one;
        }

        if (parseInt(document.getElementById('tuner_req_score').value) > 0 && parseInt(document.getElementById('tuner_req_score').value) < 100) {
                def_tuner_require_phase_two = document.getElementById('tuner_req_score').value;
        } else {
                document.getElementById('tuner_req_score').value = def_tuner_require_phase_two;
        }

        if (parseInt(document.getElementById('tuner_votes_one').value) > 1) {
                def_tuner_min_votes_one = document.getElementById('tuner_votes_one').value;
        } else {
                document.getElementById('tuner_votes_one').value = def_tuner_min_votes_one;
        }

        if (parseInt(document.getElementById('tuner_votes_two').value) > 1) {
                def_tuner_min_votes_two = document.getElementById('tuner_votes_two').value;
        } else {
                document.getElementById('tuner_votes_two').value = def_tuner_min_votes_two;
        }

        $.ajax({
                type: "GET",
                url: "/backend/tuner_save.php?def_tuner_accuracy_weight=" + def_tuner_accuracy_weight + "&def_tuner_require_phase_one=" + def_tuner_require_phase_one + "&def_tuner_require_phase_two=" + def_tuner_require_phase_two + "&def_tuner_min_votes_one=" + def_tuner_min_votes_one + "&def_tuner_min_votes_two=" + def_tuner_min_votes_two,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        alert('Botvidsson brain saved');
                                        document.getElementById('loader').style.display = 'none';
                                } else {
                                        document.getElementById('loader').style.display = 'none';
                                        alert(status);
                                }
                        });
                }
        });

}

function messengerWrite() {
        if (document.getElementById('messenger-id').value != '') {
                var msg_text = document.getElementById('msg-text').value;
                if (msg_text.length > 1) {
                        $('#modal-messenger-ui-input-button').css("opacity", "0.3");
                        $('#msg-text').prop('readonly', true);
                        if (messenger_writing == 0) {
                                messenger_writing = 1;
                                $.ajax({
                                        type: "POST",
                                        url: "/backend/sendmsg.php",
                                        data: { id: document.getElementById('messenger-id').value, text: msg_text },
                                        dataType: "xml",
                                        success: function (xml) {
                                                $(xml).find('root').each(function () {
                                                        var status = $(this).find('status').text();
                                                        if (status == 'OK') {
                                                                document.getElementById('msg-text').value = '';
                                                                document.getElementById('msg-text').setAttribute('style', '');
                                                                $('#msg-text').prop('readonly', false);
                                                                messengerLoad(document.getElementById('messenger-id').value, 0);
                                                                messengerHeight();
                                                                messenger_writing = 0;
                                                                mixpanel.track('Sent a message');
                                                        } else {
                                                                $('#modal-messenger-ui-input-button').css("opacity", "1");
                                                                $('#msg-text').prop('readonly', false);
                                                                alert(status);
                                                                messenger_writing = 0;
                                                        }
                                                });
                                        }
                                });

                        }

                } else {
                        alert('Message is too short');
                }
        } else {
                alert('No message to reply to');
        }
}

function messengerMembers() {
        if (document.getElementById('messenger-id').value != '') {
                modal('messengermembers:' + document.getElementById('messenger-id').value + ':', '1', '2');
        } else {
                alert('No message open');
        }
}

function messengerBack() {
        if (msgopen != '') {
                $('#msgitem-' + msgopen).removeClass("modal-messenger-messagelist-item-open");
                msgopen = '';

                $('#messenger-controlcenter').css("display", "inline");
                $('#messenger-members').css("display", "none");
                $('#messenger-delete').css("display", "none");
                $('#messenger-back').css("display", "none");
                $('#modal-messenger-ui-messagelisttd').css("display", "table-cell");
                $('#modal-messenger-ui-messagetd').css("display", "none");
        }
}

function messengerDelete() {
        if (document.getElementById('messenger-id').value != '') {
                $.ajax({
                        type: "GET",
                        url: "/backend/deletemsg.php?id=" + document.getElementById('messenger-id').value,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                modal('messenger', '1');
                                        }
                                });
                        }
                });
        } else {
                alert('No message open');
        }
}

function messengerLoad(id, initialload) {
        //$('#modal-messenger-ui-message').html('Loading message...');

        if (msgopen != '') {
                $('#msgitem-' + msgopen).removeClass("modal-messenger-messagelist-item-open");

                document.getElementById('msg-text').value = '';
                document.getElementById('msg-text').setAttribute('style', '');

        }

        $('#msgitem-' + id).addClass("modal-messenger-messagelist-item-open");
        msgopen = id;
        document.getElementById('messenger-id').value = id;
        $.ajax({
                type: "GET",
                url: "/backend/messenger_load.php?id=" + id + "&i=" + initialload + "&t=" + document.getElementById('messenger-loadfrom').value,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var data = $(this).find('data').text();
                                var last = $(this).find('last').text();
                                var people = $(this).find('people').text();
                                var mass = $(this).find('mass').text();
                                if (status == 'OK') {
                                        if (initialload != 0) { $('#modal-messenger-ui-message').html(data); } else { $('#modal-messenger-ui-message').append(data); }
                                        if (mass == '1') {
                                                $('#msg-text').prop('readonly', true);
                                                $('#modal-messenger-ui-write').fadeOut();
                                        } else {
                                                $('#msg-text').prop('readonly', false);
                                                $('#modal-messenger-ui-write').fadeIn();
                                        }
                                        setTimeout('messengerScroll(\'' + initialload + '\');', 100);
                                        document.getElementById('messenger-loadfrom').value = last;
                                        $('#messenger-delete').fadeIn();
                                        messengerHeight();
                                        $('#msgitem-' + id).removeClass("modal-messenger-messagelist-item-unread");
                                        $('#msgimg-' + id).removeClass("modal-messenger-messagelist-item-img-unread");
                                        $('#msg-text').focus();
                                        if (parseInt(people) > 0) { $('#messenger-members').fadeIn(); } else { $('#messenger-members').fadeOut(); }
                                        if (document.getElementById('messenger-back') != null) {
                                                $('#messenger-controlcenter').css("display", "none");
                                                $('#messenger-back').css("display", "inline");
                                                $('#modal-messenger-ui-messagelisttd').css("display", "none");
                                                $('#modal-messenger-ui-messagetd').css("display", "table-cell");
                                        }
                                        mixpanel.track('Opened a message');
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function messengerScroll(initialload) {
        if (initialload != 0) { $("#modal-messenger-ui-message").animate({ scrollTop: $('#modal-messenger-ui-message').prop("scrollHeight") }, 1); } else { $("#modal-messenger-ui-message").animate({ scrollTop: $('#modal-messenger-ui-message').prop("scrollHeight") }, 1000); }
}

var savepermtimer;

function savePermissions(user_id, groups) {
        var groupsa = groups.split(",");
        var membership = '';
        for (i = 0; i < groupsa.length; i++) {
                if (document.getElementById('member-' + user_id + '-' + groupsa[i]).checked == 1) {
                        if (membership) { membership += ','; }
                        membership += groupsa[i];
                }
        }
        $.ajax({
                type: "GET",
                url: "/backend/savepermissions.php?id=" + user_id + "&groups=" + membership,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        $('#savepermissions').fadeIn();
                                        clearTimeout(savepermtimer);
                                        savepermtimer = setTimeout('$(\'#savepermissions\').fadeOut();', 2000);
                                } else {
                                        alert(status);
                                }
                        });
                }
        });


}

function setsale(id) {
        if (document.getElementById('sale-' + id) != null) {
                var sale = 0;
                if (document.getElementById('sale-' + id).checked == 1) {
                        sale = 1;
                }
                $.ajax({
                        type: "GET",
                        url: "/backend/setsale.php?id=" + id + "&sale=" + sale,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}

function amblogout() {
        $.ajax({
                type: "GET",
                url: "/backend/ambassador_logout.php",
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        location.href = '/ambassador';
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function ambdelete(id) {
        $('#loader').fadeIn();
        $.ajax({
                type: "GET",
                url: "/backend/ambdelete.php?id=" + id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        location.href = '/ambassador';
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function amblogin(id) {
        $.ajax({
                type: "GET",
                url: "/backend/ambassador_login.php?id=" + id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        location.href = '/';
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function tunerLoad() {
        $('#loader').fadeIn();

        if (parseInt(document.getElementById('tuner_accuracy_weight').value) > 0 && parseInt(document.getElementById('tuner_accuracy_weight').value) < 100) {
                def_tuner_accuracy_weight = document.getElementById('tuner_accuracy_weight').value;
        } else {
                document.getElementById('tuner_accuracy_weight').value = def_tuner_accuracy_weight;
        }

        if (parseInt(document.getElementById('tuner_req_percent').value) > 0 && parseInt(document.getElementById('tuner_req_percent').value) < 100) {
                def_tuner_require_phase_one = document.getElementById('tuner_req_percent').value;
        } else {
                document.getElementById('tuner_req_percent').value = def_tuner_require_phase_one;
        }

        if (parseInt(document.getElementById('tuner_req_score').value) > 0 && parseInt(document.getElementById('tuner_req_score').value) < 100) {
                def_tuner_require_phase_two = document.getElementById('tuner_req_score').value;
        } else {
                document.getElementById('tuner_req_score').value = def_tuner_require_phase_two;
        }

        if (parseInt(document.getElementById('tuner_votes_one').value) > 1) {
                def_tuner_min_votes_one = document.getElementById('tuner_votes_one').value;
        } else {
                document.getElementById('tuner_votes_one').value = def_tuner_min_votes_one;
        }

        if (parseInt(document.getElementById('tuner_votes_two').value) > 1) {
                def_tuner_min_votes_two = document.getElementById('tuner_votes_two').value;
        } else {
                document.getElementById('tuner_votes_two').value = def_tuner_min_votes_two;
        }

        var weight_mode = '';

        if (document.getElementById('tuner_weight_mode').value == "cat") {
                weight_mode = 'cat';
        }

        $.ajax({
                type: "GET",
                url: "/backend/tuner_load.php?weight_mode=" + weight_mode + "&weight=" + def_tuner_accuracy_weight + "&percent=" + def_tuner_require_phase_one + "&score=" + def_tuner_require_phase_two + "&votes_one=" + def_tuner_min_votes_one + "&votes_two=" + def_tuner_min_votes_two,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var data = $(this).find('data').text();
                                if (status == 'OK') {
                                        $('#loader').fadeOut();
                                        $('#tuner-main').html(data);
                                } else {
                                        alert(status);
                                }
                        });
                }
        });

}

function addTags(tag) {
        tag = tag.toUpperCase();

        var tagcheck = tag.split(' ').join('');

        if (tag != '' && tagcheck != '') {

                var currenttags = document.getElementById('editphoto-data-4-tags').value;
                var tagstring = currenttags.split(',');

                var addtag = 1;

                tagstring.forEach(function (element) {
                        if (element == tag) {
                                addtag = 0;
                        }
                });

                if (addtag == 1) {
                        if (document.getElementById('editphoto-data-4-tags').value == '') {
                                var newtagstring = tag;
                                document.getElementById('editphoto-tags').innerHTML = '';
                        } else {
                                var newtagstring = currenttags + ',' + tag;
                        }
                        document.getElementById('editphoto-tags').innerHTML += '<span class="modal-editphoto-tag" onclick="removeTag(\'' + tag + '\');">' + tag + ' <span class="modal-editphoto-tag-x">&#215;</span></span> ';
                        document.getElementById('editphoto-data-4-tags').value = newtagstring;
                        if (document.getElementById('suggested-tag-' + tag) != null) {
                                $('#suggested-tag-' + tag).remove();
                                if (document.getElementById('editphoto-suggestedtags').innerHTML == 'Suggested tags: &nbsp; ') {
                                        document.getElementById('editphoto-suggestedtags').innerHTML = '';
                                }
                        }
                        tagsuggestions(tag);
                }

                document.getElementById('editphoto-data-4').value = '';
                setTimeout('document.getElementById(\'editphoto-data-4\').focus();', 100);
        }
}

function addFreetextTag(tag) {
        $('#dynamic-added-tags').html('');
        if (tag.length > 2) {
                addDynamicTag(tag.toUpperCase());
        }
}

function saveExtraTags(id) {
        $.ajax({
                type: "POST",
                url: me + "/backend/saveextratags.php",
                data: { pic_id: id, extratags: document.getElementById('extratags').value },
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        modal('tag:' + id + ':');
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function saveExtraTag() {
        var tag = document.getElementById('extratag').value;
        if (tag.length > 1) {
                if (document.getElementById('tag-' + tag) == null) {
                        addDynamicTag(tag.toUpperCase());
                        if (document.getElementById('extratags').value != '') {
                                document.getElementById('extratags').value = document.getElementById('extratags').value + ',';
                        }
                        document.getElementById('extratags').value = document.getElementById('extratags').value + tag.toUpperCase();
                }
        }
        document.getElementById('extratag').value = '';
        document.getElementById('extratag-addtag').style.display = 'none';
        document.getElementById('extratag-finished').style.display = 'block';
}

function addFreetextTagMulti(tag) {
        $('#dynamic-added-tags').html('');
        var multi_tags = '';
        $(".answerselected").each(function (index) {
                var elementid = $(this).attr("id");
                var rawid = elementid.replace('answerselected-', '');
                if (document.getElementById(elementid) != null) {
                        if (document.getElementById(elementid).value == '1') {
                                var multi_addtags = document.getElementById('answertags-' + rawid).value;
                                if (multi_addtags != '') {
                                        var i = 0;
                                        var multi_addtagsa = multi_addtags.split(',');
                                        for (i = 0; i < multi_addtagsa.length; i++) {
                                                addDynamicTag(multi_addtagsa[i]);
                                                if (multi_tags != '') { multi_tags += ','; }
                                                multi_tags += multi_addtagsa[i];
                                        }
                                }
                        }
                }
        });
        if (tag.length > 2) {
                if (multi_tags != '') { multi_tags += ','; }
                multi_tags += tag;
                addDynamicTag(tag.toUpperCase());
        }
        document.getElementById('multi-tags').value = multi_tags;
        document.getElementById('multi-tags-translated').value = '1';
}

function markAnswer2(module_id, answer_id, answer_limit, tags, freetext) {
        if (document.getElementById('answerselected-' + answer_id).value == '0') {
                document.getElementById('answerselected-' + answer_id).value = '1';
                $('#answer-' + answer_id).addClass('tag-answer-selected');
                if (document.getElementById(freetext) != null) {
                        $('#' + freetext).css("display", "block");
                        $('#freetexts').fadeIn();
                        document.getElementById('multi-answer-id').value = answer_id;
                }
        } else {
                document.getElementById('answerselected-' + answer_id).value = '0';
                $('#answer-' + answer_id).removeClass('tag-answer-selected');
                if (document.getElementById(freetext) != null) {
                        document.getElementById('answer-freetext-' + answer_id).value = '';
                        $('#' + freetext).css("display", "none");
                        $('#freetexts').fadeOut();
                        document.getElementById('multi-answer-id').value = '';
                }
        }
}

function markAnswer(module_id, answer_id, answer_limit, tags, freetext) {
        if (document.getElementById('answerselected-' + answer_id).value == '0') {
                if (parseInt(answer_limit) == 0 || parseInt(answer_limit) > 0 && parseInt(answer_limit) > parseInt(document.getElementById('multi-selected').value)) {
                        document.getElementById('answerselected-' + answer_id).value = '1';
                        $('#answer-' + answer_id).addClass('tag-answer-selected');
                        if (document.getElementById(freetext) != null) {
                                $('#' + freetext).css("display", "block");
                                $('#freetexts').fadeIn();
                        }
                } else {
                        alert('Maximum ' + answer_limit + ' options can be selected');
                }
        } else {
                document.getElementById('answerselected-' + answer_id).value = '0';
                $('#answer-' + answer_id).removeClass('tag-answer-selected');
                if (document.getElementById(freetext) != null) {
                        document.getElementById('answer-freetext-' + answer_id).value = '';
                        $('#' + freetext).css("display", "none");
                        $('#freetexts').fadeOut();
                }
        }
        $('#dynamic-added-tags').html('');
        var selected_all = 0;
        var selected_ids = '';
        var multi_tags = '';
        $(".answerselected").each(function (index) {
                var elementid = $(this).attr("id");
                var rawid = elementid.replace('answerselected-', '');
                if (document.getElementById(elementid) != null) {
                        if (document.getElementById(elementid).value == '1') {
                                selected_all++;
                                if (selected_ids != '') { selected_ids += ','; }
                                selected_ids += rawid;
                                var multi_addtags = document.getElementById('answertags-' + rawid).value;
                                if (multi_addtags != '') {
                                        var i = 0;
                                        var multi_addtagsa = multi_addtags.split(',');
                                        for (i = 0; i < multi_addtagsa.length; i++) {
                                                addDynamicTag(multi_addtagsa[i]);
                                                if (multi_tags != '') { multi_tags += ','; }
                                                multi_tags += multi_addtagsa[i];
                                        }
                                }
                        }
                }
        });

        $(".freetextmulti").each(function (index) {
                var elementid = $(this).attr("id");
                var rawid = elementid.replace('answerselected-', '');
                if (document.getElementById(elementid) != null) {
                        var tag = document.getElementById(elementid).value;
                        if (tag.length > 2) {
                                addDynamicTag(tag.toUpperCase());
                                if (multi_tags != '') { multi_tags += ','; }
                                multi_tags += tag.toUpperCase();
                        }
                }
        });

        document.getElementById('multi-selected').value = selected_all;
        document.getElementById('multi-selectedids').value = selected_ids;
        document.getElementById('multi-tags').value = multi_tags;
}

function addDynamicTag(tag) {
        if (document.getElementById('tag-' + tag) == null) {
                $('#dynamic-added-tags').append('<span id="tag-' + tag + '" class="tag-addedtag">' + tag + '</span> ');
        }
}

function closeWelcome() {
        $('#welcometo1x').animate({
                bottom: "-500px"
        }, 1000);
        $.ajax({
                type: "GET",
                url: "/backend/gamma.php",
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                        });
                }
        });
}

function saveLang(id) {
        var savelang = document.getElementById('languageselection').value;
        $.ajax({
                type: "GET",
                url: "/backend/savelang.php?lang=" + savelang,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        modal('tag:' + id + ':');
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function tagBack(id) {
        $.ajax({
                type: "GET",
                url: "/backend/tagback.php" + "?id=" + id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        modal('tag:' + id + ':');
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function saveFreetextAnswer() {
        var pic_id = document.getElementById('multi-pic-id').value;
        var module_id = document.getElementById('multi-module-id').value;
        var answer_id = document.getElementById('multi-answer-id').value;
        var answer_text = document.getElementById('answer-freetext-' + answer_id).value;
        $.ajax({
                type: "GET",
                url: "/backend/saveanswerfreetext.php?module_id=" + module_id + "&answer_freetext=" + answer_text + "&pic_id=" + pic_id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        modal('tag:' + pic_id + ':');
                                } else {
                                        alert(status);
                                }
                        });
                }
        });

}

function saveDropdownAnswer() {
        var module_id = document.getElementById('multi-module-id').value;
        var pic_id = document.getElementById('multi-pic-id').value;
        var tags = document.getElementById('multi-tags').value;
        if (document.getElementById('multi-answer-id-' + module_id) != null) {
                if (document.getElementById('multi-answer-id-' + module_id).value != '') {
                        $.ajax({
                                type: "GET",
                                url: "/backend/saveanswer.php?module_id=" + module_id + "&answer_id=" + document.getElementById('multi-answer-id-' + module_id).value + "&pic_id=" + pic_id + "&tags=" + tags,
                                dataType: "xml",
                                success: function (xml) {
                                        $(xml).find('root').each(function () {
                                                var status = $(this).find('status').text();
                                                if (status == 'OK') {
                                                        modal('tag:' + pic_id + ':');
                                                } else {
                                                        alert(status);
                                                }
                                        });
                                }
                        });

                } else { alert('Please select an option'); }
        }
}

function saveAnswerSingleFreetext() {
        var module_id = document.getElementById('multi-module-id').value;
        var pic_id = document.getElementById('multi-pic-id').value;
        var answer_id = document.getElementById('multi-answer-id').value;
        var tagtext = document.getElementById('answer-freetext-' + answer_id).value;

        $.ajax({
                type: "GET",
                url: "/backend/saveanswer.php?module_id=" + module_id + "&answer_id=" + answer_id + "&pic_id=" + pic_id + "&tags=" + tagtext.toUpperCase(),
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        modal('tag:' + pic_id + ':');
                                } else {
                                        alert(status);
                                }
                        });
                }
        });


}

function saveMultiAnswer() {
        var module_id = document.getElementById('multi-module-id').value;
        var selected_ids = document.getElementById('multi-selectedids').value;
        var pic_id = document.getElementById('multi-pic-id').value;
        var tags = document.getElementById('multi-tags').value;
        var translated = '0';

        if (document.getElementById('multi-tags-translated').value == '1') {
                translated = '1';
        }

        $.ajax({
                type: "GET",
                url: "/backend/saveanswermulti.php?module_id=" + module_id + "&answer_ids=" + selected_ids + "&pic_id=" + pic_id + "&tags=" + tags + "&translated=" + translated,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        modal('tag:' + pic_id + ':');
                                } else {
                                        alert(status);
                                }
                        });
                }
        });

}

function addTagsDropdown(answer_id) {
        $('#dynamic-added-tags').html('');
        var dvalue = $('#' + answer_id + ' option:selected').text();
        if (dvalue != '-- Please select --') {
                addDynamicTag(dvalue.toUpperCase());
                document.getElementById('multi-tags').value = dvalue.toUpperCase();
        } else {
                document.getElementById('multi-tags').value = '';
        }
}

function saveAnswer(module_id, answer_id, pic_id, tags) {
        $.ajax({
                type: "GET",
                url: "/backend/saveanswer.php?module_id=" + module_id + "&answer_id=" + answer_id + "&pic_id=" + pic_id + "&tags=" + tags,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        modal('tag:' + pic_id + ':');
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function tagsuggestions(tag) {
        var currenttags = document.getElementById('editphoto-data-4-tags').value;
        if (tag == '' && currenttags == '') {
                document.getElementById('editphoto-suggestedtags').innerHTML = originalsuggestions;
        } else {
                $.ajax({
                        type: "GET",
                        url: "/backend/tagsuggestions.php?current=" + currenttags + "&tag=" + tag,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var data = $(this).find('data').text();
                                        if (status == 'OK') {
                                                if (data != '') {
                                                        if (originalsuggestions == '') {
                                                                originalsuggestions = document.getElementById('editphoto-suggestedtags').innerHTML;
                                                        }
                                                        document.getElementById('editphoto-suggestedtags').innerHTML = 'Suggested tags: &nbsp; ' + data;
                                                }
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}

function removeTag(tag) {
        var currenttags = document.getElementById('editphoto-data-4-tags').value;
        var tagstring = currenttags.split(',');
        var newtagstring = '';

        document.getElementById('editphoto-tags').innerHTML = '';

        tagstring.forEach(function (element) {
                if (element != tag) {
                        if (newtagstring == '') {
                                newtagstring = element;
                        } else {
                                newtagstring += ',' + element;
                        }
                        document.getElementById('editphoto-tags').innerHTML += '<span class="modal-editphoto-tag" onclick="removeTag(\'' + element + '\');">' + element + ' <span class="modal-editphoto-tag-x">&#215;</span></span>';
                }
        });
        document.getElementById('editphoto-data-4-tags').value = newtagstring;
        if (newtagstring == '') {
                document.getElementById('editphoto-tags').innerHTML = 'Start typing and press enter to add tags';
        }
        setTimeout('document.getElementById(\'editphoto-data-4\').focus();', 100);
        tagsuggestions('');
}

function editPhotoStepBack(step) {
        var thisstep = parseInt(step) + 1;
        if (document.getElementById('editphoto-' + step) != null) {
                $('#editphoto-' + thisstep).css("display", "none");
        }
        $('#editphoto-' + step).fadeIn();
        $('#editphoto-data-' + step).focus();
}

function editPhotoStep(step, id, data) {

        var savedata = '';

        if (step == 2) {
                savedata = document.getElementById('editphoto-data-1').value;
        }

        if (step == 3) {
                savedata = document.getElementById('editphoto-data-2').value;
        }

        if (step == 4) {
                savedata = document.getElementById('editphoto-data-3').value;
        }

        if (step == 5) {
                savedata = document.getElementById('editphoto-data-4-tags').value;
        }


        if (document.getElementById('editphoto-' + step) != null) {

                var proceed = 1;

                if (step == 4 && document.getElementById('editphoto-data-3').value == '') {
                        proceed = 0;
                }

                if (step == 4 && document.getElementById('editphoto-data-3').value != '') {
                        if (document.getElementById('suggested-tags-' + document.getElementById('editphoto-data-3').value) != null) {
                                var stags1 = document.getElementById('suggested-tags-' + document.getElementById('editphoto-data-3').value).value;
                                var suggestedtags = stags1.split(',');
                                $('#editphoto-suggestedtags').html('Suggested tags: &nbsp; ');
                                suggestedtags.forEach(function (element) {
                                        $('#editphoto-suggestedtags').append('<span class="modal-editphoto-step-subdata-tag" id="suggested-tag-' + element + '" onclick="addTags(\'' + element + '\');">' + element + '</span> ');
                                });
                        }
                }

                if (proceed == 1) {


                        $.ajax({
                                type: "POST",
                                url: "/backend/photowizardstep.php",
                                data: { step: step, data: savedata, id: id },
                                dataType: "xml",
                                success: function (xml) {
                                        $(xml).find('root').each(function () {
                                                var status = $(this).find('status').text();
                                                if (status == 'OK') {

                                                        var prevstep = parseInt(step) - 1;
                                                        if (prevstep > 0) {
                                                                $('#editphoto-' + prevstep).css("display", "none");
                                                        }
                                                        $('#editphoto-' + step).fadeIn();
                                                        $('#editphoto-data-' + step).focus();

                                                } else { alert(status); }


                                        });
                                }
                        });




                } else {
                        alert('This step is mandatory');
                }

        } else {

                if (step == 6 && data != '') {
                        var img_forsale = data;
                }

                $.ajax({
                        type: "POST",
                        url: me + "/backend/savephoto.php",
                        data: { id: id, title: document.getElementById('editphoto-data-1').value, desc: document.getElementById('editphoto-data-2').value, cat: document.getElementById('editphoto-data-3').value, tags: document.getElementById('editphoto-data-4-tags').value, forsale: img_forsale },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                if (document.getElementById('directory-uploader-area') == null) {
                                                        modal('editphoto:' + id, '', '2');
                                                } else {
                                                        location.href = '/directory';
                                                }
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });

        }

}

function taggerSortOptions(module_id) {
        $.ajax({
                type: "POST",
                url: me + "/backend/tagger_sort.php",
                data: { module_id: module_id },
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        taggerRefresh();
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function taggerChildLink(module_id, answer_id) {
        $.ajax({
                type: "POST",
                url: me + "/backend/tagger_childlink.php",
                data: { module_id: module_id, answer_id: answer_id },
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        closeModal();
                                        taggerRefresh();
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function taggerChildMove(module_id, answer_id, direction) {
        $.ajax({
                type: "POST",
                url: me + "/backend/tagger_childmove.php",
                data: { module_id: module_id, answer_id: answer_id, direction: direction },
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        taggerRefresh();
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}


function taggerChildDelete(module_id, answer_id) {
        var agree = confirm('Do you want to remove this followup question?');
        if (agree) {
                $.ajax({
                        type: "POST",
                        url: me + "/backend/tagger_childdelete.php",
                        data: { module_id: module_id, answer_id: answer_id },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                taggerRefresh();
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}

function taggerRemoveModule(id) {
        $.ajax({
                type: "POST",
                url: me + "/backend/tagger_removemodule.php",
                data: { id: id },
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        closeModal();
                                        taggerRefresh();
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function taggerRemoveOption(id) {
        $.ajax({
                type: "POST",
                url: me + "/backend/tagger_removeoption.php",
                data: { id: id },
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        closeModal();
                                        taggerRefresh();
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function taggerSaveOption(id) {
        var tagself = '0';
        var freetext = '0';
        if (document.getElementById('option-freetext').checked == 1) {
                freetext = '1';
        }
        if (document.getElementById('option-tagself').checked == 1) {
                tagself = '1';
        }
        $.ajax({
                type: "POST",
                url: me + "/backend/tagger_saveoption.php",
                data: { id: id, name: document.getElementById('option-name').value, order: document.getElementById('option-order').value, tags: document.getElementById('option-tags').value, tagself: tagself, child: document.getElementById('option-child').value, freetext: freetext, cat: document.getElementById('option-cat').value, child_priority: document.getElementById('option-child-priority').value },
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        closeModal();
                                        taggerRefresh();
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function taggerSaveModule(id) {
        var mod_order = '1';
        if (document.getElementById('mod-order') != null) { mod_order = document.getElementById('mod-order').value; }
        $.ajax({
                type: "POST",
                url: me + "/backend/tagger_savemodule.php",
                data: { id: id, label: document.getElementById('mod-internal-label').value, name: document.getElementById('mod-question').value, order: mod_order, answer_type: document.getElementById('mod-answer-type').value, answer_limit: document.getElementById('mod-answer-limit').value },
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        closeModal();
                                        taggerRefresh();
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}


function sendFeedback() {
        $.ajax({
                type: "POST",
                url: me + "/backend/sitefeedback.php",
                data: { text: document.getElementById('feedback_text').value },
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        alert('Thanks!');
                                        closeModal();
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function savePhotoDetails(id) {
        $.ajax({
                type: "POST",
                url: me + "/backend/savephotolong.php",

                data: { id: id, p_title: document.getElementById('editphoto_title').value, p_desc: document.getElementById('editphoto_desc').value, p_cat: document.getElementById('editphoto_category').value, p_tags: document.getElementById('editphoto_tags').value, pi_extra: document.getElementById('editphoto_extra').value, pi_focal: document.getElementById('editphoto_focal').value, pi_shutter: document.getElementById('editphoto_shutter').value, pi_iso: document.getElementById('editphoto_iso').value, pi_aperture: document.getElementById('editphoto_aperture').value, pi_exposure: document.getElementById('editphoto_exposure').value, pi_flash: document.getElementById('editphoto_flash').value, pi_filter: document.getElementById('editphoto_filter').value, pi_tripod: document.getElementById('editphoto_tripod').value, pi_camera: document.getElementById('editphoto_camera').value, pi_lens: document.getElementById('editphoto_lens').value },
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        $('#photodetailssave').html('<span style="color: var(--jade); font-weight: 800; padding: 0px 0px 0px 10px;font-family: proxima-nova;">Saved</span>');
                                        setTimeout('$(\'#photodetailssave\').html(\'\');', 2000);
                                        mixpanel.track('Saved details about a photo');
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function postCritique(id) {
        if (document.getElementById('critique_desc').value.length > 499) {
                $.ajax({
                        type: "POST",
                        url: me + "/backend/postcritique.php",
                        data: { id: id, desc: document.getElementById('critique_desc').value },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                mixpanel.track('Posted a photo for critique', { "Link": "https://1x.com/photo/" + id });
                                                location.href = '/directory/' + id;
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}

function starPreview(critique_id, loop) {
        var start_loop = 1;
        while (start_loop != 6) {
                if (loop >= start_loop) {
                        $('#rating_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_active.png");
                        $('#rating_' + critique_id + '_' + start_loop).addClass("curation_feedback_ratings_star_active");
                } else {
                        $('#rating_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_inactive.png");
                        $('#rating_' + critique_id + '_' + start_loop).removeClass("curation_feedback_ratings_star_active");
                }
                start_loop++;
        }
}

function curationProgress(perc) {

        if (perc >= 0) {
                setTimeout('activateDot(1);', 10);
        }
        if (perc >= 33) {
                setTimeout('activateDot(2);', 500);
        }
        if (perc >= 66) {
                setTimeout('activateDot(3);', 1000);
        }
        if (perc == 100) {
                setTimeout('activateDot(4);', 2000);
        }

        $('#modal-editphoto-curationprogress-front').animate({
                width: perc + "%"
        }, 2000);

        $('#modal-editphoto-curationprogress-dotnow').animate({
                marginLeft: perc + "%"
        }, 2000);


}

function activateDot(dot) {
        $('#modal-editphoto-curationprogress-dot' + dot).animate({
                backgroundColor: "#10c191"
        }, 500);
        $('#modal-editphoto-curationprogress-label' + dot).animate({
                color: "#10c191"
        }, 500);
}

function starRestore(critique_id) {
        var loop = document.getElementById('critique_' + critique_id).value;

        var start_loop = 1;
        while (start_loop != 6) {
                if (loop >= start_loop) {
                        $('#rating_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_active.png");
                } else {
                        $('#rating_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_inactive.png");
                }
                start_loop++;
        }
}

function starSet(critique_id, loop) {
        var start_loop = 1;
        while (start_loop != 6) {
                if (loop >= start_loop) {
                        $('#rating_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_active.png");
                } else {
                        $('#rating_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_inactive.png");
                }
                start_loop++;
        }
        document.getElementById('critique_' + critique_id).value = loop;
}

function starPreview2(critique_id, loop) {
        if (starblock != '1') {
                var start_loop = 1;
                while (start_loop != 6) {
                        if (loop >= start_loop) {
                                $('#rating2_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_active.png");
                                $('#rating2_' + critique_id + '_' + start_loop).addClass("curation_feedback_ratings_star2_active");
                        } else {
                                $('#rating2_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_inactive.png");
                                $('#rating2_' + critique_id + '_' + start_loop).removeClass("curation_feedback_ratings_star2_active");
                        }
                        start_loop++;
                }
        }
}

function starRestore2(critique_id) {
        var loop = document.getElementById('critique_' + critique_id).value;

        var start_loop = 1;
        while (start_loop != 6) {
                if (loop >= start_loop) {
                        $('#rating2_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_active.png");
                        $('#rating2_' + critique_id + '_' + start_loop).addClass("curation_feedback_ratings_star2_active");
                } else {
                        $('#rating2_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_inactive.png");
                        $('#rating2_' + critique_id + '_' + start_loop).removeClass("curation_feedback_ratings_star2_active");
                }
                start_loop++;
        }
}

function starSet2(critique_id, loop) {
        var start_loop = 1;
        starblock = 1;
        while (start_loop != 6) {
                if (loop >= start_loop) {
                        $('#rating2_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_active.png");
                        $('#rating_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_active.png");
                } else {
                        $('#rating2_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_inactive.png");
                        $('#rating_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_inactive.png");
                }
                start_loop++;
        }
        document.getElementById('critique_' + critique_id).value = loop;
        var animation = "fadeOutUp";
        if (critique_id != 8) {
                var next = parseInt(critique_id) + 1;
                $('#curation_critique_request_' + critique_id).css("opacity", "1");
                setTimeout('$(\'#curation_critique_request_' + critique_id + '\').css("display","none");', 500);
                setTimeout('$(\'#curation_critique_request_' + next + '\').css("display","block"); starblock = \'0\';', 500);
                $('.curation_feedback_ratings_star2_active').addClass("animated faster");
                $('.curation_feedback_ratings_star2_active').addClass(animation);
        } else {
                $('#curation_critique_request_' + critique_id).fadeOut();
                $('.curation_feedback_ratings_star2_active').addClass("animated faster");
                $('.curation_feedback_ratings_star2_active').addClass(animation);
                setTimeout('critiqueReview();', 500);
        }
}

function starPreview4(critique_id, loop) {
        if (starblock != '1') {
                var start_loop = 1;
                while (start_loop != 6) {
                        if (loop >= start_loop) {
                                $('#rating4_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_active.png");
                                //$('#rating4_' + critique_id + '_' + start_loop).addClass("curation_feedback_ratings_star2_active");
                        } else {
                                $('#rating4_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_inactive.png");
                                //$('#rating4_' + critique_id + '_' + start_loop).removeClass("curation_feedback_ratings_star2_active");
                        }
                        start_loop++;
                }
        }
}

function starRestore4(critique_id) {
        var loop = document.getElementById('critique_' + critique_id).value;

        var start_loop = 1;
        while (start_loop != 6) {
                if (loop >= start_loop) {
                        $('#rating4_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_active.png");
                } else {
                        $('#rating4_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_inactive.png");
                }
                start_loop++;
        }
}

function starSet4(critique_id, loop) {
        var start_loop = 1;
        while (start_loop != 6) {
                if (loop >= start_loop) {
                        $('#rating4_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_active.png");
                } else {
                        $('#rating4_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_inactive.png");
                }
                start_loop++;
        }
        document.getElementById('critique_' + critique_id).value = loop;
}


function starPreview3(critique_id, loop) {
        var start_loop = 1;
        while (start_loop != 6) {
                if (loop >= start_loop) {
                        $('#rating_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_active.png");
                } else {
                        $('#rating_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_inactive.png");
                }
                start_loop++;
        }
}


function starRestore3(critique_id) {
        var loop = document.getElementById('critiquereview_' + critique_id).value;

        var start_loop = 1;
        while (start_loop != 6) {
                if (loop >= start_loop) {
                        $('#rating_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_active.png");
                        $('#rating_' + critique_id + '_' + start_loop).addClass("curation_feedback_ratings_star2_active");
                } else {
                        $('#rating_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_inactive.png");
                        $('#rating_' + critique_id + '_' + start_loop).removeClass("curation_feedback_ratings_star2_active");
                }
                start_loop++;
        }
}

function starSet3(critique_id, loop) {
        var start_loop = 1;
        starblock = 1;
        while (start_loop != 6) {
                if (loop >= start_loop) {
                        $('#rating_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_active.png");
                } else {
                        $('#rating_' + critique_id + '_' + start_loop).attr("src", "/assets/img/star_inactive.png");
                }
                start_loop++;
        }
        document.getElementById('critiquereview_' + critique_id).value = loop;
        $('#curation_feedback_btn_send').css("opacity", "1");

}


var exhibitionsclosetimer;

var exhibeditrunning = '0';

function saveExhibSettings() {

        if (document.getElementById('setting_visible').checked == 1) { var s_visible = '1'; } else { var s_visible = '0'; }
        if (document.getElementById('setting_auto_add').checked == 1) { var s_auto_add = '1'; } else { var s_auto_add = '0'; }
        if (document.getElementById('setting_default_exhib').checked == 1) { var s_default_exhib = '1'; } else { var s_default_exhib = '0'; }

        exhibedit(document.getElementById('exhibition_id').value, 'settings:' + s_visible + ':' + s_auto_add + ':' + s_default_exhib + ':');
}

function setFeeling(id, color) {
        var current_feel = document.getElementById('feeling').value;
        if (current_feel != '') {
                $('#fe_' + current_feel).css("boxShadow", "unset");
        }
        $('#fe_' + id).css("boxShadow", "0px 0px 20px #" + color);
        document.getElementById('feeling').value = id;
        $('#curation_feedback_btn_send').css("opacity", "1");
}

function exhibedit(e_id, action) {
        if (exhibeditrunning == '0') {
                exhibeditrunning = '1';
                $.ajax({
                        type: "GET",
                        url: "/backend/exhibedit.php?id=" + e_id + "&action=" + action,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var state = $(this).find('state').text();
                                        if (status == 'OK') {
                                                exhibeditrunning = '0';
                                                var actiona = action.split(":");
                                                if (actiona[0] == "deleteobject") {
                                                        $('#drag-' + actiona[1]).remove();
                                                        $('#drag2-' + actiona[1]).remove();
                                                        sortable('#photos-feed');
                                                        sortable('#editor2');
                                                }
                                                if (actiona[0] == "align") {
                                                        if (actiona[3] == '1' || actiona[3] == '2') {
                                                                var setclass = 'photos-feed-' + actiona[2] + '-' + actiona[3];
                                                                $('#align-' + actiona[1]).attr("class", setclass);
                                                                $('#img-' + actiona[1]).removeClass("extrabig");
                                                        }

                                                        if (actiona[3] == '3' && actiona[2] == 'landscape') {
                                                                $('#align-' + actiona[1]).toggleClass("extrabig");
                                                                $('#img-' + actiona[1]).toggleClass("extrabig");
                                                        }
                                                }
                                        } else {
                                                var actiona = action.split(":");
                                                if (actiona[0] == "settings" && state == '1') {
                                                        document.getElementById('setting_default_exhib').checked = 1;
                                                }
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}

function deletePhoto(id) {
        var agree = confirm('Are you sure?');
        if (agree) {
                $.ajax({
                        type: "GET",
                        url: "/backend/deletephoto.php?id=" + id,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                mixpanel.track('Deleted a photo');
                                                if (document.getElementById('directory-uploader-area') == null) {
                                                        closeModal2();
                                                        setTimeout('modal(\'uploader\',\'1\');', 500);
                                                } else {
                                                        location.href = '/directory';
                                                }
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}

function exhibitions(user_id) {
        if (document.getElementById('exhibitions_inner') == null) {
                $('#exhibitions').html('<div class="exhibition_window" id="exhibitions_inner"><div style="padding: 50px; font-weight: 300; text-align: center;">Loading...</div></div>');
                $.ajax({
                        type: "GET",
                        url: "/backend/exhibitions.php?id=" + user_id,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var data = $(this).find('data').text();
                                        if (status == 'OK') {
                                                $('#exhibitions').html(data);
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}

function exhibitionsClose() {
        clearTimeout(exhibitionsclosetimer);
        exhibitionsclosetimer = setTimeout('exhibitionsCloseDo();', 200);
}

function exhibitionsCloseDo() {
        $('#exhibitions').html("");
}

function sendCurators(id) {
        $.ajax({
                type: "GET",
                url: "/backend/sendcurators.php?id=" + id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var imgid = $(this).find('imgid').text();
                                var imgfile = $(this).find('imgfile').text();
                                if (status == 'OK') {
                                        mixpanel.track('Sent a photo to curation', { "Photo": "https://1x.com/photo/" + id });
                                        if (modalopen == 'directory') {
                                                modal('directory', '1');
                                        } else {
                                                if (app == "front") {
                                                        //supernotification();
                                                } else {
                                                        modal('editphoto:' + id + ':', '', '2');
                                                }
                                        }
                                        if (document.getElementById('curationbubble') != null) {
                                                $('#curationbubble').html('<div class="curationbubble_popout"><table border="0" class="curationbubble_popout_progress" cellpadding="0" cellspacing="0"><tbody><tr><td colspan="3" valign="bottom"><div class="curationbubble_popout_line"><div class="curationbubble_popout_line_grey"></div><div style="width: 10px" class="curationbubble_popout_line_green" id="curationbubble_popout_line_green"></div></div></td><td></td><td rowspan="2"><center><div class="curationbubble_popout_progress_pop">1%</div><div class="curationbubble_popout_progress_poplabel">More popular than other photos according to member curators</div></center></td></tr><tr><td valign="top" class="curationbubble_popout_progress"><span class="curationbubble_popout_progress_dot_green"><i class="fas fa-circle"></i></span>Uploaded</td><td valign="top" class="curationbubble_popout_progress"><span class="curationbubble_popout_progress_dot_green"><i class="fas fa-circle"></i></span>Member curators</td><td valign="top" class="curationbubble_popout_progress"><span class="curationbubble_popout_progress_dot_green"><i class="fas fa-circle"></i></span>Expert curators</td><td valign="top" class="curationbubble_popout_progress2"><span class="curationbubble_popout_progress_dot"><i class="fas fa-circle"></i></span>Result</td></tr></tbody></table></div><div onclick="" class="circular"><div class="inner" style="background: url(/images/user/' + imgfile + '-sq.jpg); background-size: cover;"></div><div class="number" id="curation_bubble_percentage">1%</div><div class="circle"><div class="bar left"><div class="progress" id="curation_bubble_left" style="transform: rotate(3.6deg);"></div></div><div class="bar right"><div class="progress" id="curation_bubble_right" style="transform: rotate(0deg);"></div></div></div></div>');
                                        }
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function search(q) {
        clearTimeout(searchtimer);
        searchtimer = setTimeout('searchDo(\'' + q + '\');', 500);
}

function searchDo(q) {
        if (q) {
                if (q != search_cache) {

                        $('#modal-search-results').html('<div style="padding: 50px 0px 50px 0px;"><table class="modal-load" width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td class="modal-load-td"><center><div class="lds-ring"><div></div><div></div><div></div><div></div></div></center></td></tr></table></div>');

                        search_cache = q;

                        $.ajax({
                                type: "GET",
                                url: "/backend/search.php?q=" + q,
                                dataType: "xml",
                                success: function (xml) {
                                        $(xml).find('root').each(function () {
                                                var status = $(this).find('status').text();
                                                var data = $(this).find('data').text();
                                                if (status == 'OK') {
                                                        $('#modal-search-results').html(data);
                                                } else {
                                                        alert(status);
                                                }
                                        });
                                }
                        });
                }
        } else {
                $('#modal-search-results').html('');
        }
}

function feelingSkip(id) {
        $.ajax({
                type: "GET",
                url: "/backend/feeling_skip.php?id=" + id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        getCurate();
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}


function critiqueSkip(id) {

        $.ajax({
                type: "GET",
                url: "/backend/critique_skip.php?id=" + id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        getCurate();
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function critiqueReviewSkip(comment_id, id) {

        $.ajax({
                type: "GET",
                url: "/backend/critique_review_skip.php?comment_id=" + comment_id + "&id=" + id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        getCurate();
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}




function showStars(message) {
        $('#starsmajor').fadeIn();
        $('#starsinner').html(message);
        loop();
}

function feedbackSkip(id) {
        $('#feedback_' + id).fadeOut('slow');
        if (curateresume_what != '') { setTimeout('curateDo(\'' + curateresume_what + '\',\'' + curateresume_id + '\');', 800); } else { $('#curation_btn_' + id).fadeIn('slow'); }
        scrollto('body', 0);
        curateresume_did = '1';
}

function critiqueSkip2(id) {
        $('#feedback_' + id).fadeOut('slow');
        scrollto('body', 0);
        setTimeout('critiqueSkip(\'' + id + '\');', 1000);
}

function critiqueStart() {
        $('#curation_critique_request_0').fadeOut();
        setTimeout('$(\'#curation_critique_request_1\').fadeIn();', 1000);
}

function critiqueReview() {
        var id = document.getElementById('feedback_id').value;
        if (typeof (window.innerWidth) == 'number') {
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
        }

        var moveup = (myHeight - $('#curate2_' + id).height()) / 2;
        $('#feedback_' + id).css("marginTop", "-" + moveup + "px");

        $('#feedback_' + id).fadeIn('slow');
        scrollto('feedback_' + id, 100);
}

function feedbackShow(id) {
        if (typeof (window.innerWidth) == 'number') {
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
        }

        var moveup = (myHeight - $('#curate2_' + id).height()) / 2;
        $('#feedback_' + id).css("marginTop", "-" + moveup + "px");
        $('#feedback_' + id).fadeIn('slow');
        $('#curation_btn_' + id).fadeOut('slow');
        scrollto('feedback_' + id, 100);
}

function feedbackSend() {
        if (document.getElementById('feedback_1').value != "" || document.getElementById('feedback_2').value != "" || document.getElementById('feedback_comment').value != '') {
                $.ajax({
                        type: "POST",
                        url: "/backend/feedback.php",
                        dataType: "xml",
                        data: { id: document.getElementById('feedback_id').value, feedback_1: document.getElementById('feedback_1').value, feedback_2: document.getElementById('feedback_2').value, feedback_comment: document.getElementById('feedback_comment').value },
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var data = $(this).find('data').text();
                                        var xp = $(this).find('xp').text();
                                        var level = $(this).find('level').text();
                                        var level_xp = $(this).find('level_xp').text();
                                        var level_name = $(this).find('level_name').text();
                                        var next_level = $(this).find('next_level').text();
                                        var next_level_xp = $(this).find('next_level_xp').text();
                                        var next_level_name = $(this).find('next_level_name').text();
                                        var next_level_xp_remaining = $(this).find('next_level_xp_remaining').text();
                                        var progress = $(this).find('progress').text();
                                        var xp_added = parseInt($(this).find('xp_added').text());
                                        var label = $(this).find('label').text();

                                        clearTimeout(curateload);
                                        if (status == 'OK') {
                                                curateresume_did = '1';
                                                $('#curation_btn_feedback').css("display", "none");
                                                if (xp_added > 0) {
                                                        if (document.getElementById('curate_level_name').value != level_name) {
                                                                setTimeout('showStars(\'<div class="stars_title2">Congratulations. You are now</div><div class="stars_title">a Curator!</div>\');', animdelay);
                                                        } else {
                                                                if (document.getElementById('curate_level').value != level) {
                                                                        //setTimeout('curateMessage(\'Congratulations, you are now a ' + label + ' ' + level + ' ' + level_name + '!\');',animdelay);
                                                                        takeover('<div class="animated pulse"><div class="takeover_inner_header">Level up!</div><div class="takeover_inner_subheader">Congratulations, you are now a ' + label + ' ' + level + ' ' + level_name + '!</div></div>', 3000);
                                                                } else {
                                                                        if (totalcurate2 > 17) {
                                                                                setTimeout('curateMessage(\'' + doinggreat[getRandomInt(doinggreat.length)] + '\');', animdelay);
                                                                                totalcurate2 = 0;
                                                                        }
                                                                }
                                                        }

                                                        document.getElementById('curate_level').value = level;
                                                        document.getElementById('curate_level_xp').value = level_xp;
                                                        document.getElementById('curate_level_name').value = level_name;

                                                        document.getElementById('curate_next_level').value = next_level;
                                                        document.getElementById('curate_next_level_xp').value = next_level_xp;
                                                        document.getElementById('curate_next_level_name').value = next_level_name;
                                                        document.getElementById('curate_next_level_xp_remaining').value = next_level_xp_remaining;

                                                        document.getElementById('curate_progress').value = progress;

                                                        document.getElementById('curate_xp').value = xp;


                                                        document.getElementById('curate_xp_today').value = parseInt(document.getElementById('curate_xp_today').value) + xp_added;

                                                        curatesession = curatesession + xp_added;

                                                        bubble(xp_added);
                                                        od3 = new Odometer({
                                                                el: document.getElementById('minibar_stats_xptoday2'),
                                                                duration: 500
                                                        });

                                                        od3.update(document.getElementById('curate_xp_today').value);

                                                        od2 = new Odometer({
                                                                el: document.getElementById('curationinterface_bar_mid_xp_mini2'),
                                                        });

                                                        od2.update(xp);
                                                }

                                                document.getElementById('curateinfo_grade').innerHTML = label + ' ' + level + ' ' + level_name;

                                                document.getElementById('curationinterface_bar_this_level_mini').innerHTML = label + ' ' + level;
                                                document.getElementById('curationinterface_bar_this_level_xp_mini').innerHTML = level_xp + xunit;
                                                document.getElementById('curationinterface_bar_next_level_mini').innerHTML = label + ' ' + next_level;
                                                document.getElementById('curationinterface_bar_next_level_xp_mini').innerHTML = next_level_xp + xunit;

                                                document.getElementById('curationinterface_bar_this_level').innerHTML = label + ' ' + level;
                                                document.getElementById('curationinterface_bar_this_level_xp').innerHTML = level_xp + xunit;
                                                document.getElementById('curationinterface_bar_next_level').innerHTML = label + ' ' + next_level;
                                                document.getElementById('curationinterface_bar_next_level_xp').innerHTML = next_level_xp + xunit;

                                                feedbackSkip(document.getElementById('feedback_id').value);

                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        } else {
                alert('Please click the main room for improvement and/or the main positive feedback or click "Skip"');
        }
}


function feelingDo(id) {
        if (document.getElementById('feeling').value != "") {
                $.ajax({
                        type: "POST",
                        url: "/backend/feeling.php",
                        dataType: "xml",
                        data: { feeling_id: document.getElementById('feeling_id').value, feeling: document.getElementById('feeling').value },
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var data = $(this).find('data').text();
                                        var xp = $(this).find('xp').text();
                                        var level = $(this).find('level').text();
                                        var level_xp = $(this).find('level_xp').text();
                                        var level_name = $(this).find('level_name').text();
                                        var next_level = $(this).find('next_level').text();
                                        var next_level_xp = $(this).find('next_level_xp').text();
                                        var next_level_name = $(this).find('next_level_name').text();
                                        var next_level_xp_remaining = $(this).find('next_level_xp_remaining').text();
                                        var progress = $(this).find('progress').text();
                                        var xp_added = parseInt($(this).find('xp_added').text());
                                        var label = $(this).find('label').text();

                                        clearTimeout(curateload);
                                        if (status == 'OK') {
                                                curateresume_did = '1';
                                                $('#curation_btn_feedback').css("display", "none");
                                                if (xp_added > 0) {
                                                        var animdelay = 5000;
                                                        if (document.getElementById('curate_level_name').value != level_name) {
                                                                setTimeout('showStars(\'<div class="stars_title2">Congratulations. You are now</div><div class="stars_title">a Curator!</div>\');', animdelay);
                                                        } else {
                                                                if (document.getElementById('curate_level').value != level) {
                                                                        //setTimeout('curateMessage(\'Congratulations, you are now a ' + label + ' ' + level + ' ' + level_name + '!\');',animdelay);
                                                                        takeover('<div class="animated pulse"><div class="takeover_inner_header">Level up!</div><div class="takeover_inner_subheader">Congratulations, you are now a ' + label + ' ' + level + ' ' + level_name + '!</div></div>', 3000);
                                                                } else {
                                                                        if (totalcurate2 > 17) {
                                                                                setTimeout('curateMessage(\'' + doinggreat[getRandomInt(doinggreat.length)] + '\');', animdelay);
                                                                                totalcurate2 = 0;
                                                                        }
                                                                }
                                                        }

                                                        document.getElementById('curate_level').value = level;
                                                        document.getElementById('curate_level_xp').value = level_xp;
                                                        document.getElementById('curate_level_name').value = level_name;

                                                        document.getElementById('curate_next_level').value = next_level;
                                                        document.getElementById('curate_next_level_xp').value = next_level_xp;
                                                        document.getElementById('curate_next_level_name').value = next_level_name;
                                                        document.getElementById('curate_next_level_xp_remaining').value = next_level_xp_remaining;

                                                        document.getElementById('curate_progress').value = progress;

                                                        document.getElementById('curate_xp').value = xp;


                                                        document.getElementById('curate_xp_today').value = parseInt(document.getElementById('curate_xp_today').value) + xp_added;

                                                        curatesession = curatesession + xp_added;

                                                        bubble(xp_added);
                                                        od3 = new Odometer({
                                                                el: document.getElementById('minibar_stats_xptoday2'),
                                                                duration: 500
                                                        });

                                                        od3.update(document.getElementById('curate_xp_today').value);

                                                        od2 = new Odometer({
                                                                el: document.getElementById('curationinterface_bar_mid_xp_mini2'),
                                                        });

                                                        od2.update(xp);
                                                }

                                                document.getElementById('curateinfo_grade').innerHTML = label + ' ' + level + ' ' + level_name;

                                                document.getElementById('curationinterface_bar_this_level_mini').innerHTML = label + ' ' + level;
                                                document.getElementById('curationinterface_bar_this_level_xp_mini').innerHTML = level_xp + xunit;
                                                document.getElementById('curationinterface_bar_next_level_mini').innerHTML = label + ' ' + next_level;
                                                document.getElementById('curationinterface_bar_next_level_xp_mini').innerHTML = next_level_xp + xunit;

                                                document.getElementById('curationinterface_bar_this_level').innerHTML = label + ' ' + level;
                                                document.getElementById('curationinterface_bar_this_level_xp').innerHTML = level_xp + xunit;
                                                document.getElementById('curationinterface_bar_next_level').innerHTML = label + ' ' + next_level;
                                                document.getElementById('curationinterface_bar_next_level_xp').innerHTML = next_level_xp + xunit;

                                                feedbackSkip(document.getElementById('feeling_id').value);
                                                scrollto('body', 0);
                                                setTimeout('getCurate();', 1000);


                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        } else {
                alert('Please click a feeling');
        }
}






function critiqueReviewDo(comment_id, id) {
        if (parseInt(document.getElementById('critiquereview_' + id).value) > 0) {
                $.ajax({
                        type: "GET",
                        url: "/backend/critique_review.php?comment_id=" + comment_id + "&id=" + id + "&grade=" + document.getElementById('critiquereview_' + id).value,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var xp = $(this).find('xp').text();
                                        var level = $(this).find('level').text();
                                        var level_xp = $(this).find('level_xp').text();
                                        var level_name = $(this).find('level_name').text();
                                        var next_level = $(this).find('next_level').text();
                                        var next_level_xp = $(this).find('next_level_xp').text();
                                        var next_level_name = $(this).find('next_level_name').text();
                                        var next_level_xp_remaining = $(this).find('next_level_xp_remaining').text();
                                        var progress = $(this).find('progress').text();
                                        var xp_added = parseInt($(this).find('xp_added').text());
                                        var label = $(this).find('label').text();

                                        if (status == 'OK') {
                                                curateresume_did = '1';
                                                $('#curation_btn_feedback').css("display", "none");
                                                if (xp_added > 0) {
                                                        var animdelay = 5000;
                                                        if (document.getElementById('curate_level_name').value != level_name) {
                                                                setTimeout('showStars(\'<div class="stars_title2">Congratulations. You are now</div><div class="stars_title">a Curator!</div>\');', animdelay);
                                                        } else {
                                                                if (document.getElementById('curate_level').value != level) {
                                                                        takeover('<div class="animated pulse"><div class="takeover_inner_header">Level up!</div><div class="takeover_inner_subheader">Congratulations, you are now a ' + label + ' ' + level + ' ' + level_name + '!</div></div>', 3000);
                                                                }
                                                        }

                                                        document.getElementById('curate_level').value = level;
                                                        document.getElementById('curate_level_xp').value = level_xp;
                                                        document.getElementById('curate_level_name').value = level_name;

                                                        document.getElementById('curate_next_level').value = next_level;
                                                        document.getElementById('curate_next_level_xp').value = next_level_xp;
                                                        document.getElementById('curate_next_level_name').value = next_level_name;
                                                        document.getElementById('curate_next_level_xp_remaining').value = next_level_xp_remaining;

                                                        document.getElementById('curate_progress').value = progress;

                                                        document.getElementById('curate_xp').value = xp;


                                                        document.getElementById('curate_xp_today').value = parseInt(document.getElementById('curate_xp_today').value) + xp_added;

                                                        curatesession = curatesession + xp_added;

                                                        bubble(xp_added, 2000);

                                                        od3 = new Odometer({
                                                                el: document.getElementById('minibar_stats_xptoday2'),
                                                                duration: 500
                                                        });

                                                        od3.update(document.getElementById('curate_xp_today').value);

                                                        od2 = new Odometer({
                                                                el: document.getElementById('curationinterface_bar_mid_xp_mini2'),
                                                        });

                                                        od2.update(xp);
                                                }

                                                document.getElementById('curateinfo_grade').innerHTML = label + ' ' + level + ' ' + level_name;

                                                document.getElementById('curationinterface_bar_this_level_mini').innerHTML = label + ' ' + level;
                                                document.getElementById('curationinterface_bar_this_level_xp_mini').innerHTML = level_xp + xunit;
                                                document.getElementById('curationinterface_bar_next_level_mini').innerHTML = label + ' ' + next_level;
                                                document.getElementById('curationinterface_bar_next_level_xp_mini').innerHTML = next_level_xp + xunit;

                                                document.getElementById('curationinterface_bar_this_level').innerHTML = label + ' ' + level;
                                                document.getElementById('curationinterface_bar_this_level_xp').innerHTML = level_xp + xunit;
                                                document.getElementById('curationinterface_bar_next_level').innerHTML = label + ' ' + next_level;
                                                document.getElementById('curationinterface_bar_next_level_xp').innerHTML = next_level_xp + xunit;


                                                $('#feedback_' + document.getElementById('feedback_id').value).fadeOut('slow');
                                                scrollto('body', 0);
                                                setTimeout('getCurate();', 1000);

                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        } else {
                alert('You must click the stars to grade the comment');
        }
}


function critiqueSend() {
        var critiqueok = 1;
        var critiqueLoop = 0;
        while (critiqueLoop != 8) {
                critiqueLoop++;
                if (parseInt(document.getElementById('critique_' + critiqueLoop).value) > 0 && parseInt(document.getElementById('critique_' + critiqueLoop).value) < 6) {
                } else {
                        critiqueok = 0;
                }
        }

        if (critiqueok == 1) {
                $.ajax({
                        type: "POST",
                        url: "/backend/critique.php",
                        dataType: "xml",
                        data: { id: document.getElementById('feedback_id').value, critique_1: document.getElementById('critique_1').value, critique_2: document.getElementById('critique_2').value, critique_3: document.getElementById('critique_3').value, critique_4: document.getElementById('critique_4').value, critique_5: document.getElementById('critique_5').value, critique_6: document.getElementById('critique_6').value, critique_7: document.getElementById('critique_7').value, critique_8: document.getElementById('critique_8').value, feedback_comment: document.getElementById('feedback_comment').value },
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var data = $(this).find('data').text();
                                        var xp = $(this).find('xp').text();
                                        var level = $(this).find('level').text();
                                        var level_xp = $(this).find('level_xp').text();
                                        var level_name = $(this).find('level_name').text();
                                        var next_level = $(this).find('next_level').text();
                                        var next_level_xp = $(this).find('next_level_xp').text();
                                        var next_level_name = $(this).find('next_level_name').text();
                                        var next_level_xp_remaining = $(this).find('next_level_xp_remaining').text();
                                        var progress = $(this).find('progress').text();
                                        var xp_added = parseInt($(this).find('xp_added').text());
                                        var label = $(this).find('label').text();

                                        clearTimeout(curateload);
                                        if (status == 'OK') {
                                                curateresume_did = '1';
                                                $('#curation_btn_feedback').css("display", "none");
                                                if (xp_added > 0) {
                                                        var animdelay = 5000;
                                                        if (document.getElementById('curate_level_name').value != level_name) {
                                                                setTimeout('showStars(\'<div class="stars_title2">Congratulations. You are now</div><div class="stars_title">a Curator!</div>\');', animdelay);
                                                        } else {
                                                                if (document.getElementById('curate_level').value != level) {
                                                                        //setTimeout('curateMessage(\'Congratulations, you are now a ' + label + ' ' + level + ' ' + level_name + '!\');',animdelay);
                                                                        takeover('<div class="animated pulse"><div class="takeover_inner_header">Level up!</div><div class="takeover_inner_subheader">Congratulations, you are now a ' + label + ' ' + level + ' ' + level_name + '!</div></div>', 3000);
                                                                }
                                                        }

                                                        document.getElementById('curate_level').value = level;
                                                        document.getElementById('curate_level_xp').value = level_xp;
                                                        document.getElementById('curate_level_name').value = level_name;

                                                        document.getElementById('curate_next_level').value = next_level;
                                                        document.getElementById('curate_next_level_xp').value = next_level_xp;
                                                        document.getElementById('curate_next_level_name').value = next_level_name;
                                                        document.getElementById('curate_next_level_xp_remaining').value = next_level_xp_remaining;

                                                        document.getElementById('curate_progress').value = progress;

                                                        document.getElementById('curate_xp').value = xp;


                                                        document.getElementById('curate_xp_today').value = parseInt(document.getElementById('curate_xp_today').value) + xp_added;

                                                        curatesession = curatesession + xp_added;

                                                        takeover('critique_thanks', 5000);
                                                        bubble(xp_added, 5000);

                                                        od3 = new Odometer({
                                                                el: document.getElementById('minibar_stats_xptoday2'),
                                                                duration: 500
                                                        });

                                                        od3.update(document.getElementById('curate_xp_today').value);

                                                        od2 = new Odometer({
                                                                el: document.getElementById('curationinterface_bar_mid_xp_mini2'),
                                                        });

                                                        od2.update(xp);
                                                }

                                                document.getElementById('curateinfo_grade').innerHTML = label + ' ' + level + ' ' + level_name;

                                                document.getElementById('curationinterface_bar_this_level_mini').innerHTML = label + ' ' + level;
                                                document.getElementById('curationinterface_bar_this_level_xp_mini').innerHTML = level_xp + xunit;
                                                document.getElementById('curationinterface_bar_next_level_mini').innerHTML = label + ' ' + next_level;
                                                document.getElementById('curationinterface_bar_next_level_xp_mini').innerHTML = next_level_xp + xunit;

                                                document.getElementById('curationinterface_bar_this_level').innerHTML = label + ' ' + level;
                                                document.getElementById('curationinterface_bar_this_level_xp').innerHTML = level_xp + xunit;
                                                document.getElementById('curationinterface_bar_next_level').innerHTML = label + ' ' + next_level;
                                                document.getElementById('curationinterface_bar_next_level_xp').innerHTML = next_level_xp + xunit;


                                                $('#feedback_' + document.getElementById('feedback_id').value).fadeOut('slow');
                                                scrollto('body', 0);
                                                if (curate_load == 0) {
                                                        setTimeout('getCurate();', 1000);
                                                } else {
                                                        setTimeout('location.href=\'/critique\';', 3500);
                                                }

                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        } else {
                alert('Please ensure you have graded all 8 categories');
        }
}


function feedbackSet(feedback_type, id) {
        if (feedback_type == '1' || feedback_type == '2') {
                if (document.getElementById('feedback_' + feedback_type).value != id) {
                        if (document.getElementById('feedback_' + feedback_type).value != '') {
                                $('#feedback_option_' + document.getElementById('feedback_' + feedback_type).value).removeClass("curation_feedback_option_active");
                                document.getElementById('feedback_' + feedback_type).value = '';
                        }
                        $('#feedback_option_' + id).addClass("curation_feedback_option_active");
                        document.getElementById('feedback_' + feedback_type).value = id;
                } else {
                        $('#feedback_option_' + document.getElementById('feedback_' + feedback_type).value).removeClass("curation_feedback_option_active");
                        document.getElementById('feedback_' + feedback_type).value = '';
                }
        }
        if (document.getElementById('feedback_1').value != '' || document.getElementById('feedback_2').value != '' || document.getElementById('feedback_comment').value != '') {
                $('#curation_feedback_btn_send').css("opacity", "1");
        } else {
                $('#curation_feedback_btn_send').css("opacity", "0.3");
        }
}


function setCurateTableSize(id) {
        if (typeof (window.innerWidth) == 'number') {
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
        }

        var myHeight2 = myHeight - 207;

        document.getElementById('curate_' + id + '_table').style.height = myHeight + 'px';
        document.getElementById('curate2_' + id).style.maxHeight = myHeight2 + 'px';
}

function setCurateTableSize2(id) {
        if (typeof (window.innerWidth) == 'number') {
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
        }

        var myHeight2 = myHeight - 307;

        document.getElementById('curate_' + id + '_table').style.height = myHeight + 'px';
        document.getElementById('curate2_' + id).style.maxHeight = myHeight2 + 'px';
}

function hideProgress() {
        $('#curationinterface_minibar').animate({
                top: "-110px"
        }, 500);
}

function fillBar(percentage, xp) {
        $('#curationinterface_bar1').animate({
                width: percentage + '%',
                backgroundColor: "#10c191"
        }, 1000);

        $('#curationinterface_bar_mid_xp').animate({
                opacity: 1
        }, 1000);

        $('#curationinterface_bar_mid_xp').html(xp + xunit);
        axp = xp;
}

function taggerRefresh() {
        if (document.getElementById('tagger-main').innerHTML == '') {
                document.getElementById('loader').style.display = 'block';
        }
        var answers_open = '';
        var modules_open = '';

        $(".tagger-module-answers").each(function (index) {
                var elementid = $(this).attr("id");
                if (document.getElementById(elementid).style.display != 'none') { answers_open += elementid.replace('answers-', '') + ':'; }
        });

        $(".tagger-module-sublevel").each(function (index) {
                var elementid = $(this).attr("id");
                if (document.getElementById(elementid).style.display != 'none') { modules_open += elementid.replace('module-', '') + ':'; }
        });

        $.ajax({
                type: "GET",
                url: "/backend/tagger_refresh.php?answers_open=" + answers_open + "&modules_open=" + modules_open,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var data = $(this).find('data').text();
                                if (status == 'OK') {
                                        $('#loader').fadeOut();
                                        $('#tagger-main').html(data);
                                } else {
                                        alert(status);
                                }
                        });
                }
        });

}

function signupExecute() {
        nloader('Creating your 1x account...');

        var invite_code = '';

        if (document.getElementById('invite_code') != null) {
                invite_code = document.getElementById('invite_code').value;
        }

        mixpanel.track('Creating account');

        $.ajax({
                type: "POST",
                url: "/backend/s_exec.php",
                data: { invite_code: invite_code, email: document.getElementById('signup-module-input-email').value, name: document.getElementById('signup-module-input-name').value, username: document.getElementById('signup-module-input-username').value, password: document.getElementById('signup-module-input-password').value, country: document.getElementById('signup-module-input-country').value, token: document.getElementById('stoken').value },
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var error = $(this).find('error').text();
                                if (status == 'OK') {
                                        mixpanel.track('Finished signup');
                                        if (document.getElementById('splan').value != 'free') {
                                                mixpanel.track('Redirecting to Stripe for payment (' + document.getElementById('splan').value + ')');
                                                startSubscriptionSCA2(document.getElementById('splan').value);
                                        } else {
                                                location.href = '/';
                                        }
                                } else {
                                        if (status == "NOK") {
                                                nloaderstop();
                                                var jerror = JSON.parse(error);
                                                if (jerror["email"]) { signupError('email', jerror["email"]); }
                                                if (jerror["name"]) { signupError('name', jerror["name"]); }
                                                if (jerror["username"]) { signupError('username', jerror["username"]); }
                                                if (jerror["password"]) { signupError('password', jerror["password"]); }
                                                if (jerror["country"]) { signupError('country', jerror["country"]); }
                                        } else {
                                                nloaderstop();
                                                alert(status);
                                        }
                                }
                        });
                }
        });

}

function signupProceed(field) {
        if (signupproceed == 0) {
                mixpanel.track('Continued signup to ' + field);
                signupRestore(field);
                $('#signup-module-button-' + field).animate({ opacity: 0.3 }, 500);
                $('#signup-module-field-status-' + field).html('<div style="position: relative; top: 10px; left: 10px;"><div class="lds-ring"><div></div><div></div><div></div><div></div></div></div>');
                $('#signup-module-input-' + field).attr('readonly', true);

                $.ajax({
                        type: "GET",
                        url: "/backend/s_proceed.php?f=" + field + "&v=" + encodeURIComponent(document.getElementById('signup-module-input-' + field).value),
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                signupOk(field);
                                        } else {
                                                signupError(field, status);
                                        }
                                });
                        }
                });
        }
}

function signupOk(field) {
        var nextf = '';
        $('#signup-module-input-' + field).attr('readonly', false);
        $('#signup-module-button-' + field).css("display", "none");
        $('#signup-module-button-' + field).css("opacity", "1");
        $('#signup-module-field-status-' + field).html('<span class="signup-module-icon-good"><i class="fas fa-check-circle"></i></span>');

        if (field == 'email') {
                nextf = 'name';
        }

        if (field == 'name') {
                nextf = 'password';
        }

        if (field == 'password') {
                nextf = 'username';
        }

        if (field == 'username') {
                nextf = 'country';
        }

        if (field == 'country') {
                $('#signup-module-' + field).css("opacity", "0.5");
                $('#signup-button-do').fadeIn();
        } else {
                if (nextf != '') {
                        $('#signup-module-' + field).css("opacity", "0.5");
                        $('#signup-module-' + nextf).css("opacity", "1");
                        $('#signup-module-' + nextf).fadeIn();
                        $('#signup-module-input-' + nextf).focus();
                        if (document.getElementById('signup-module-input-' + nextf).value != '') {
                                $('#signup-module-button-' + nextf).css("display", "block");
                        }
                }
        }
}

function signupError(field, error) {
        $('#signup-module-' + field).css("opacity", "1");
        $('#signup-button-do').fadeOut();
        $('#signup-module-input-' + field).attr('readonly', false);
        $('#signup-module-button-' + field).animate({ opacity: 1 }, 500);
        $('#signup-module-subtext-' + field).html('<span style="color: var(--curatered); font-weight: 800;">' + error + '</span>');
        $('#signup-module-field-' + field).removeClass("signup-module-field");
        $('#signup-module-field-' + field).addClass("signup-module-field-error");
        $('#signup-module-field-status-' + field).html('<span class="signup-module-icon"><i class="fas fa-exclamation-circle"></i></span>');
        document.getElementById('signup-module-input-' + field).focus();
}

function signupRestore(field) {
        $('#signup-module-' + field).css("opacity", "1");
        $('#signup-module-field-status-' + field).html('');
        $('#signup-module-field-' + field).removeClass("signup-module-field-error");
        $('#signup-module-field-' + field).addClass("signup-module-field");
        $('#signup-module-subtext-' + field).html(document.getElementById('subtext-' + field).value);

        $('div.signup-module-button').each(function () {
                if (this.id != 'signup-module-button-' + field) { $('#' + this.id).css("display", "none"); }
        });
}

function signuptype(field) {
        clearTimeout(signuptimer);
        signuptimer = setTimeout('signuptypedo(\'' + field + '\');', 50);
}

function signuptypedo(field) {
        if (document.getElementById('signup-module-input-' + field).value != '') {
                $('#signup-module-header-' + field).animate({ opacity: 1 }, 500);
                $('#signup-module-button-' + field).fadeIn();
        } else {
                $('#signup-module-header-' + field).animate({ opacity: 0 }, 100);
                $('#signup-module-button-' + field).fadeOut();
        }
}

function startsignup(plan, e) {

        e.target.style.opacity = '0.3';

        e.preventDefault();
        grecaptcha.ready(function () {
                grecaptcha.execute('6Lc4kd4ZAAAAAISalhrF3nyrdXXbXMfzwmno8F68', { action: 'submit' }).then(function (token) {

                        mixpanel.track('Started signup with plan ' + plan);

                        document.getElementById('stoken').value = token;
                        document.getElementById('splan').value = plan;

                        var theight = $('#pro_page').height() + 140;
                        $('#pro_page').animate({
                                opacity: 0
                        }, 500);

                        setTimeout('$(\'#pro_page\').css("display","none");', 500);
                        setTimeout('$(\'#signup_container\').fadeIn();', 500);

                        $('html, body').animate({
                                scrollTop: 0
                        }, 500);

                        setTimeout('$(\'#signup-module-input-email\').focus();', 500);

                        $('#navi-button-menu').fadeOut('slow');


                });
        });
}

function startsignup2() {
        var plan = 'free';
        grecaptcha.ready(function () {
                grecaptcha.execute('6Lc4kd4ZAAAAAISalhrF3nyrdXXbXMfzwmno8F68', { action: 'submit' }).then(function (token) {

                        document.getElementById('stoken').value = token;
                        document.getElementById('splan').value = plan;

                        var theight = $('#pro_page').height() + 140;
                        $('#pro_page').animate({
                                opacity: 0
                        }, 500);

                        setTimeout('$(\'#pro_page\').css("display","none");', 500);
                        setTimeout('$(\'#signup_container\').fadeIn();', 500);

                        $('html, body').animate({
                                scrollTop: 0
                        }, 500);

                        setTimeout('$(\'#signup-module-input-email\').focus();', 500);

                        $('#menubutton').fadeOut('slow');


                });
        });
}

function signupDo(plan, step, data) {

}

function startCurate() {
        var theight = $('#curate_welcome').height() + 140;
        $('#curate_welcome').animate({
                marginTop: "-" + theight + "px",
                opacity: 0
        }, 1000);
        document.getElementById('loader').style.display = 'block';
        setTimeout('getCurate();', 1000);
        setTimeout('hideWelcome();', 1000);
        $('#menubutton').fadeOut('slow');
        $('#middlelogos').fadeOut('slow');
        $('#curationbubble').fadeOut();
        $('#curateinfo').fadeIn('slow');
        $('#curatecontainer').fadeIn('slow');
        $('#navi-buttons').fadeOut('slow');
        $('#rightbubble-notification2').fadeOut('slow');
        $('#rightbubble-message2').fadeOut('slow');
        startxp = axp;
        curatesession = 0;
        mixpanel.track('Start curation');
}

function startCurateImmediately(id) {
        var theight = $('#curate_welcome').height() + 140;
        $('#curate_welcome').css("marginTop", "-" + theight + "px");
        document.getElementById('loader').style.display = 'block';
        setTimeout('getCurate();', 300);
        setTimeout('hideWelcome();', 300);
        $('#menubutton').css("display", "none");
        $('#middlelogos').css("display", "none");
        $('#curateinfo').css("display", "block");
        $('#curatecontainer').css("display", "block");
        $('#navi-buttons').css("display", "none");
        startxp = axp;
        curatesession = 0;
        curate_load = id;
}

function exitCuration() {
        $('#curate_welcome').css("display", "block");
        $('#middlelogos').fadeIn('slow');
        $('#curateinfo').fadeOut('slow');
        $('#navi-buttons').fadeIn('slow');
        $('#curationbubble').fadeIn();
        $('#curatecontainer').fadeOut('slow');
        $('#curatecontainer').html('');
        var theight = $('#curate_welcome').height() + 140;
        setTimeout('showWelcome();', 600);
        if (curatesession > 0) {
                setTimeout('showWelcome2();', 1800);
        }
        setTimeout('fillBar(\'' + document.getElementById('curate_progress').value + '\',\'' + document.getElementById('curate_xp').value + '\');', 1000);
}

function showWelcome() {
        $('#curate_welcome').animate({
                marginTop: "0px",
                opacity: 1
        }, 1000);
}

function showWelcome2() {
        $('#curationinterface_stats').html('<div class="curationinterface_stats_inner animated bounce">This session <span style="font-weight: 800;">+' + curatesession + xunit + '</span></div>');
}

function curateMessage(message) {
        $('#curatemessage').html('<div class="animated tada"><b>' + message + '</b></div>');
        $('#curateinfo').fadeOut();
        $('#curatemessage').fadeIn();
        clearTimeout(curatemessagetimer);
        curatemessagetimer = setTimeout('curateMessageHide();', 3000);
}

function curateMessageHide() {
        $('#curateinfo').fadeIn();
        $('#curatemessage').fadeOut();
}

function hideWelcome() {
        $('#curate_welcome').css("display", "none");
}

function getCurate(what, id) {

        if (what == '1') { var animdelay = 500; }
        if (what == '2') { var animdelay = 3000; }
        if (what == '3') { var animdelay = 5000; }

        $.ajax({
                type: "GET",
                url: "/backend/curate.php?id=" + id + "&what=" + what + "&curate_load=" + curate_load,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var data = $(this).find('data').text();
                                var xp = $(this).find('xp').text();
                                var level = $(this).find('level').text();
                                var level_xp = $(this).find('level_xp').text();
                                var level_name = $(this).find('level_name').text();
                                var next_level = $(this).find('next_level').text();
                                var next_level_xp = $(this).find('next_level_xp').text();
                                var next_level_name = $(this).find('next_level_name').text();
                                var next_level_xp_remaining = $(this).find('next_level_xp_remaining').text();
                                var progress = $(this).find('progress').text();
                                var xp_added = parseInt($(this).find('xp_added').text());
                                var label = $(this).find('label').text();

                                clearTimeout(curateload);
                                if (status == 'OK') {
                                        if (xp_added > 0) {


                                                if (document.getElementById('curate_level_name').value != level_name) {
                                                        setTimeout('showStars(\'<div class="stars_title2">Congratulations. You are now</div><div class="stars_title">a Curator!</div>\');', animdelay);
                                                } else {
                                                        if (document.getElementById('curate_level').value != level) {
                                                                //setTimeout('curateMessage(\'Congratulations, you are now a ' + label + ' ' + level + ' ' + level_name + '!\');',animdelay);
                                                                takeover('<div class="animated pulse"><div class="takeover_inner_header">Level up!</div><div class="takeover_inner_subheader">Congratulations, you are now a ' + label + ' ' + level + ' ' + level_name + '!</div></div>', 3000);
                                                        } else {
                                                                if (totalcurate2 > 17) {
                                                                        setTimeout('curateMessage(\'' + doinggreat[getRandomInt(doinggreat.length)] + '\');', animdelay);
                                                                        totalcurate2 = 0;
                                                                }
                                                        }
                                                }

                                                document.getElementById('curate_level').value = level;
                                                document.getElementById('curate_level_xp').value = level_xp;
                                                document.getElementById('curate_level_name').value = level_name;

                                                document.getElementById('curate_next_level').value = next_level;
                                                document.getElementById('curate_next_level_xp').value = next_level_xp;
                                                document.getElementById('curate_next_level_name').value = next_level_name;
                                                document.getElementById('curate_next_level_xp_remaining').value = next_level_xp_remaining;

                                                document.getElementById('curate_progress').value = progress;

                                                document.getElementById('curate_xp').value = xp;


                                                document.getElementById('curate_xp_today').value = parseInt(document.getElementById('curate_xp_today').value) + xp_added;

                                                curatesession = curatesession + xp_added;

                                                bubble(xp_added);

                                                od3 = new Odometer({
                                                        el: document.getElementById('minibar_stats_xptoday2'),
                                                        duration: 500
                                                });

                                                od3.update(document.getElementById('curate_xp_today').value);

                                                od2 = new Odometer({
                                                        el: document.getElementById('curationinterface_bar_mid_xp_mini2'),
                                                });

                                                od2.update(xp);
                                        }

                                        document.getElementById('curateinfo_grade').innerHTML = label + ' ' + level + ' ' + level_name;

                                        document.getElementById('curationinterface_bar_this_level_mini').innerHTML = label + ' ' + level;
                                        document.getElementById('curationinterface_bar_this_level_xp_mini').innerHTML = level_xp + xunit;
                                        document.getElementById('curationinterface_bar_next_level_mini').innerHTML = label + ' ' + next_level;
                                        document.getElementById('curationinterface_bar_next_level_xp_mini').innerHTML = next_level_xp + xunit;

                                        document.getElementById('curationinterface_bar_this_level').innerHTML = label + ' ' + level;
                                        document.getElementById('curationinterface_bar_this_level_xp').innerHTML = level_xp + xunit;
                                        document.getElementById('curationinterface_bar_next_level').innerHTML = label + ' ' + next_level;
                                        document.getElementById('curationinterface_bar_next_level_xp').innerHTML = next_level_xp + xunit;

                                        document.getElementById('loader').style.display = 'none';
                                        $('#curatecontainer').html(data);
                                        totalcurate++;
                                        totalcurate2++;
                                        if (totalcurate > 2500) {
                                                clearTimeout(progresstimer);

                                                if (typeof (window.innerWidth) == 'number') {
                                                        myWidth = window.innerWidth;
                                                        myHeight = window.innerHeight;
                                                } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                                                        myWidth = document.documentElement.clientWidth;
                                                        myHeight = document.documentElement.clientHeight;
                                                } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                                                        myWidth = document.body.clientWidth;
                                                        myHeight = document.body.clientHeight;
                                                }


                                                var thewidth = $('#curationinterface_minibar').width();
                                                var setwidth = Math.round((myWidth / 2) - (thewidth / 2));
                                                $('#curationinterface_minibar').css("left", setwidth + 'px');
                                                $('#curationinterface_minibar').animate({
                                                        top: "0px"
                                                }, 500);
                                                progresstimer = setTimeout('hideProgress();', 5000);


                                                $('#curationinterface_bar1_mini').animate({
                                                        width: progress + '%',
                                                        backgroundColor: "#10c191"
                                                }, 1000);

                                                $('#curationinterface_bar_mid_xp_mini').animate({
                                                        opacity: 1
                                                }, 1000);

                                                od = new Odometer({
                                                        el: document.getElementById('curationinterface_bar_mid_xp_mini'),
                                                });

                                                od.update(xp);
                                                totalcurate = 0;
                                        }
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function getRandomInt(max) {
        return Math.floor(Math.random() * Math.floor(max));
}

function bgGreen() {
        $('#body').animate({
                backgroundColor: "#00B1B0"
        }, 500);
        $('#curateinfo').fadeOut('slow');
}
function bgWhite() {
        if (darkmode == 1) {
                $('#body').animate({
                        backgroundColor: "#222222"
                }, 500);
                $('#curateinfo').fadeIn('slow');
        } else {
                $('#body').animate({
                        backgroundColor: "#ffffff"
                }, 500);
                $('#curateinfo').fadeIn('slow');
        }
}

var autofeedback = 0;

function curateDo(what, id) {
        if (getRandomInt(15) == 1 && curateresume_did == '' && autofeedback > 10) {
                curateresume_what = what;
                curateresume_id = id;
                feedbackShow(id);
                autofeedback = 0;
        } else {
                curateresume_what = '';
                curateresume_id = '';
                curateresume_did = '';
                autofeedback++;
                $('#curate2_' + id).addClass("animated");
                if (what == '1') {
                        $('#redoverlay').fadeIn("fast");
                        setTimeout('$(\'#curate2_' + id + '\').addClass("fadeOutDownBig");', 200);
                        setTimeout('$(\'#redoverlay\').fadeOut();', 200);
                        var animdelay = 500;
                }
                if (what == '2') {
                        setTimeout('$(\'#curate2_' + id + '\').addClass("zoomOut");', 1000);
                        var animdelay = 3000;
                        $('#animations_target').html('<div class="animations_target_inner animated delay-1s zoomOut"><svg class="checkmark" width="100%" height="100%" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" fill-opacity="1"><circle class="circle" cx="16" cy="16" r="16" style="fill: #00B1B0; stroke: none;" /><path class="check" d="M 9 16 L 14 21 L 23 12" style="fill: none; stroke: #fff; stroke-width: 1;" /></svg></div>');
                        setTimeout('$(\'#animations_target\').html(\'<div class="animations_target_inner_div"><table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%"><tr><td><div class="animations_target_inner_text animated zoomIn">Publish</div></td></tr></table></div>\');', 1000);
                        setTimeout('bgGreen();', 1000);
                        setTimeout('bgWhite();', 3000);
                        setTimeout('$(\'#animations_target\').html(\'\');', 3000);
                        var checkTimeLine = anime.timeline({
                                autoplay: true,
                                direction: "alternate",
                                loop: false
                        });

                        // add events to timeline
                        checkTimeLine
                                .add({
                                        targets: ".checkmark",
                                        scale: [
                                                { value: [0.7, 1], duration: 100, easing: "easeOutQuad" }
                                        ]
                                })
                                .add({
                                        targets: ".check",
                                        strokeDashoffset: {
                                                value: [anime.setDashoffset, 0]
                                        },
                                        duration: 500,
                                        delay: 1,
                                        easing: "easeOutQuad"
                                });

                }
                if (what == '3') {
                        $('#curate2_' + id).animate({
                                opacity: ".7"
                        }, 500);
                        setTimeout('$(\'#curate2_' + id + '\').addClass("zoomOut");', 2000);
                        var animdelay = 5000;
                        $('#animations_target').html('<div class="animations_target_inner animated delay-2s zoomOut"><svg class="checkmark" width="100%" height="100%" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" fill-opacity="1"><circle class="circle" cx="16" cy="16" r="16" style="fill: #FEC84D; stroke: none;" /><path class="check" d="m15.999999,5.726939l2.980252,6.148997l6.769749,0.935188l-4.927002,4.735254l1.202503,6.726686l-6.025502,-3.223188l-6.026311,3.223188l1.203313,-6.726686l-4.927001,-4.735254l6.769751,-0.935188l2.980248,-6.148997z" style="fill: #fff; transform-origin: 50% 50%; transform-box: fill-box;" /></svg></div>');
                        //setTimeout('$(\'#animations_target\').html(\'<div class="animations_target_inner_text animated zoomIn" style="color: #000;">Sublime</div>\');',2000);
                        setTimeout('$(\'#animations_target\').html(\'<div class="animations_target_inner_div"><table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%"><tr><td><div class="animations_target_inner_text animated zoomIn" style="color: #D4AF37; text-shadow: 0px 0px 30px #FEC84D;">Sublime</div></td></tr></table></div>\');', 2000);
                        setTimeout('$(\'#curateinfo\').fadeOut(\'slow\');', 2000);
                        setTimeout('$(\'#curateinfo\').fadeIn(\'slow\');', 5000);
                        setTimeout('$(\'#animations_target\').html(\'\');', 5000);
                        var checkTimeLine = anime.timeline({
                                autoplay: true,
                                direction: "alternate",
                                loop: false
                        });

                        // add events to timeline
                        checkTimeLine
                                .add({
                                        targets: ".checkmark",
                                        scale: [
                                                { value: [0.7, 1], duration: 100, easing: "easeOutQuad" }
                                        ]
                                })
                                .add({
                                        targets: ".check",
                                        scale: [
                                                { value: [0, 1], duration: 800, easing: "spring(1, 80, 10, 0)" }
                                        ]

                                });

                        setTimeout('confetti.start();', 700);
                        setTimeout('confetti.stop();', 4000);
                }
                $('#curation_btn_' + id).fadeOut('slow', function () { });
                curateload = setTimeout('document.getElementById(\'loader\').style.display = \'block\';', animdelay + 700);
                setTimeout('getCurate(\'' + what + '\',\'' + id + '\');', animdelay);
        }
}

function overviewopen(id) {
        overviewclose();
        openPhoto(id);
}

function bodyscroll() {
        stopscroll = '0';
        $('body').css("overflow", "");
}

function bodystopscroll() {
        stopscroll = '1';
        $('body').css("overflow", "hidden");
}

function getForumPosts(topic_id, from) {
        document.getElementById('loader').style.display = 'block';
        var found = 0;
        var lastloadedmsg = 0;
        var lastread;
        $.ajax({
                type: "GET",
                url: "/backend/forumposts.php?id=" + topic_id + "&from=" + from,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                lastread = $(this).find('lastread').text();
                                if (status != 'OK') {
                                        alert(status);
                                } else {
                                        document.getElementById('forum_thread_loader').style.display = 'none';
                                        document.getElementById('loader').style.display = 'none';
                                        document.getElementById('forum_reply').style.display = 'block';
                                }
                        });
                        $(xml).find('post').each(function () {
                                var id = $(this).find('id').text();
                                var name = $(this).find('name').text();
                                var post_user = $(this).find('post_user').text();
                                var post_name = $(this).find('post_name').text();
                                var profilepic = $(this).find('profilepic').text();
                                var when = $(this).find('when').text();
                                var text = $(this).find('text').text();
                                var rawtext = $(this).find('rawtext').text();
                                var published = $(this).find('published').text();
                                var followers = $(this).find('followers').text();
                                var msgunread = $(this).find('unread').text();
                                var canedit = $(this).find('canedit').text();
                                var candelete = $(this).find('candelete').text();
                                var shortname = $(this).find('shortname').text();
                                var lastedit = $(this).find('lastedit').text();
                                var title = $(this).find('title').text();
                                found++;
                                if (msgunread == '1') { msgunread = '<span style="margin: 0px 0.5em 0px 0px;"><i class="fas fa-circle"></i></span>'; } else { msgunread = ''; }
                                var l_data = '<div id="forummsg_' + id + '" class="forum-post"><div id="rawtext_' + id + '" style="display: none;">' + rawtext + '</div><input type="hidden" id="forum_author_' + id + '" value="' + post_name + '"><a class="blacklink" href="/' + post_user + '"><div class="forumpost_header"><table border="0" cellpadding="0" cellspacing="0"><tr><td width="50"><img border="0" style="width: 40px; height: 40px;" src="https://seuppcdn01.1x.com/images/profile/' + profilepic + '-square.jpg"></td><td valign="top"><div class="forumpost_name">' + post_name + '</div><div class="forum-post-data">' + msgunread + title + when;
                                l_data += '</div></td></tr></table></div></a><div class="forumpost_text" id="forum_text_' + id + '">' + text + '</div><div class="forumpost_buttons"><span class="lastedited" id="lastedited_' + id + '">' + lastedit + '</span>';
                                if (canedit == '1') {
                                        if (found == 1 && from == 0) {
                                                l_data += '<span class="button lightgrey xsmall" onclick="editMsg(\'' + id + '\',\'' + topic_id + '\',\'1\');">Edit</span> ';
                                        } else {
                                                l_data += '<span class="button lightgrey xsmall" onclick="editMsg(\'' + id + '\',\'' + topic_id + '\',\'0\');">Edit</span> ';
                                        }
                                }
                                if (candelete == '1') {
                                        if (found == 1 && from == 0) {
                                                l_data += '<span class="button lightgrey xsmall" onclick="deleteTopic(\'' + topic_id + '\',\'' + shortname + '\');">Delete topic</span> ';
                                        } else {
                                                l_data += '<span class="button lightgrey xsmall" onclick="deleteForumMsg(\'' + id + '\');">Delete</span> ';
                                        }
                                }
                                l_data += '<span class="button lightgrey xsmall" onclick="quoteMsg(\'' + id + '\');">Quote</span> <span class="btn btn-sm btn-secondary" onclick="scrolltotop();"><i class="pe-7s-up-arrow" style="position: relative; top: 1px;"></i></span></div></div>';
                                $('#forum_thread').append(l_data);
                                lastloadedmsg = id;
                        });

                        if (parseInt(lastloadedmsg) > parseInt(document.getElementById('forum_thread_latest').value)) {
                                document.getElementById('forum_thread_latest').value = lastloadedmsg;
                        }

                        if (parseInt(from) > 0) {
                                scrollto('forummsg_' + lastloadedmsg, 60);
                        }
                        if (parseInt(lastread) > 0 && parseInt(from) == 0) {
                                scrollto('forummsg_' + lastread, 60);
                        }
                }
        });
}

function createTopic(forum_id) {
        if (forum_id) {
                if (document.getElementById('topic_name').value != '' && document.getElementById('topic_text').value) {
                        $.ajax({
                                type: "POST",
                                url: "/backend/forumcreate.php",
                                data: { forum_id: forum_id, name: document.getElementById('topic_name').value, text: document.getElementById('topic_text').value },
                                dataType: "xml",
                                success: function (xml) {
                                        $(xml).find('root').each(function () {
                                                var status = $(this).find('status').text();
                                                var url = $(this).find('url').text();
                                                if (status == 'OK') {
                                                        location.href = url;
                                                } else {
                                                        alert(status);
                                                }
                                        });
                                }
                        });
                } else {
                        alert('You must write a topic name and text');
                }
        }
}


function deleteForumMsg(id) {
        if (document.getElementById('forummsg_' + id) != null) {
                $.ajax({
                        type: "GET",
                        url: "/backend/deleteforummsg.php?id=" + id,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                $('#forummsg_' + id).fadeOut();
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}


function deleteTopic(id, shortname) {
        var agree = confirm('Are you sure you want to delete the entire topic and all messages?');
        if (agree) {
                $.ajax({
                        type: "GET",
                        url: "/backend/deleteforumtopic.php?id=" + id,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                location.href = '/forum/' + shortname + '/deleted';
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}


function getThreads(forum_id, forum_name, from) {

        if (typeof (window.innerWidth) == 'number') {
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
        }

        myWidth = myWidth - 150;

        var found = 0;
        document.getElementById('forum_threadlist_loadmore').style.display = 'none';
        $.ajax({
                type: "GET",
                url: "/backend/threads.php?id=" + forum_id + "&from=" + from,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status != 'OK') {
                                        alert(status);
                                } else {
                                        if (from == 0) {
                                                document.getElementById('forum_threadlist_loader').style.display = 'none';
                                        }
                                }
                        });
                        $(xml).find('thread').each(function () {
                                var id = $(this).find('id').text();
                                var name = $(this).find('name').text();
                                var lastpost_user = $(this).find('lastpost_user').text();
                                var lastpost_name = $(this).find('lastpost_name').text();
                                var profilepic = $(this).find('profilepic').text();
                                var sticky = $(this).find('sticky').text();
                                var locked = $(this).find('locked').text();
                                var when = $(this).find('when').text();
                                var unread = $(this).find('unread').text();
                                var shortname = $(this).find('shortname').text();
                                found++;
                                var threadmyWidth = myWidth;
                                if (unread == 1) { threadmyWidth = threadmyWidth - 30; var forum_name_class = 'forum_name_unread'; } else { var forum_name_class = 'forum_name_read'; }
                                var l_data = '<div class="forum-thread" style="cursor: pointer;" onclick="openThread(\'/forum/' + shortname + '/' + id + '\',\'' + id + '\');" id="thread_' + id + '">';
                                l_data += '<table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td width="57"><img src="https://seuppcdn01.1x.com/images/profile/' + profilepic + '-square.jpg" style="width: 40px; height: 40px;"></td><td valign="top"><div class="' + forum_name_class + '" id="forum_name_' + id + '" style="max-width: ' + threadmyWidth + 'px;">' + name;
                                if (parseInt(unread) > 0) { l_data += ' <span id="unread_' + id + '" class="forum-new">New</span>'; }
                                l_data += '</div><div style="font-weight: 400; font-size: 0.8em; color: #888;"><span style="padding: 0px 0px 0px 2px;">' + lastpost_name + '</span> <span style="padding: 0px 0px 0px 2px;">' + when + '</span></div> ';
                                if (sticky == '1') {
                                }
                                if (locked == '1') {
                                }


                                l_data += '</td></tr></table></div>';
                                $('#forum_threadlist').append(l_data);
                        });
                        if (found == 50) {
                                document.getElementById('forum_threadlist_loadmore').style.display = 'block';
                        }
                        if (found == 0 && from == 0) {
                                $('#forum_threadlist').append('<div class="list-group-item"><div style="font-size: 2em; color: #aaa; padding: 1em; font-weight: 300; text-align: center;"><div style="color: #ccc;font-size: 3em;"><i class="pe-7s-chat"></i></div>No topics found</div></div>');
                        }
                        document.getElementById('forum_threadlist_loaded').value = parseInt(document.getElementById('forum_threadlist_loaded').value) + found;
                }
        });
}

function openThread(url, id) {
        $('#forum_name_' + id).removeClass("forum_name_unread");
        $('#forum_name_' + id).addClass("forum_name_read");
        if (document.getElementById('unread_' + id) != null) {
                document.getElementById('unread_' + id).style.display = 'none';
        }
        location.href = url;
}


function fauximage(id, img) {

        if (typeof (window.innerWidth) == 'number') {
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
        }

        if (document.getElementById('spinner-' + id) != null) {
                document.getElementById('faux-' + id).innerHTML = '<img src="' + img + '">';
                if (document.getElementById('spinner-' + id + '-2') != null) {
                        var jumpin = ((document.getElementById('spinner-' + id + '-1').offsetWidth) - myWidth) + 80;
                        if (jumpin > 0) {
                                document.getElementById('spinner-' + id).scrollLeft = jumpin;
                        }
                }
        }
}

function closeLastOpenedPhoto() {
        if (lastopenedphoto != '') {
                openPhoto(lastopenedphoto);
        }
}

function openPhotoSafe(id) {
        var elementid = event.srcElement.id;
        if (elementid.includes('heart')) {
        } else {
                if (elementid.includes('buyprintlink') || elementid.includes('followbuttons')) {
                } else {
                        openPhoto(id);
                }
        }
}

function openPhoto(id) {
        // alldataopen

        // profile-container-img-

        if ($('#imgdata-' + id).hasClass('alldataclosed')) {
                if (document.getElementById('profile-container-img-' + id) != null) {
                        $('#profile-container-img-' + id).removeClass("profile-container-img-open");
                }
                $('.alldata-' + id).removeClass("alldataclosed");
                $('#img-' + id).removeClass("img-open");
                $('#imgcontainer-' + id).removeClass("container-open");
                $('#photodata-' + id).html('');
                lastopenedphoto = '';
                urlupdate(lastopenurl);
                lastopenurl = '';
        } else {
                if (document.getElementById('profile-container-img-' + id) != null) {
                        $('#profile-container-img-' + id).addClass("profile-container-img-open");
                }
                $('.alldata-' + id).addClass("alldataclosed");
                $('#img-' + id).addClass("img-open");
                $('#imgcontainer-' + id).addClass("container-open");
                document.getElementById('imgcontainer-' + id).onmousedown = blockRightClick;
                document.getElementById('imgcontainer-' + id).oncontextmenu = blockDownload;

                $([document.documentElement, document.body]).animate({
                        scrollTop: $('#imgcontainer-' + id).offset().top + 1
                }, 500);

                pdata('photoinfo:' + id, 'photodata-' + id);
                lastopenedphoto = id;

        }
}

function closeModal() {
        var close = 1;
        if (document.getElementById('areyousure') != null) {
                var agree = confirm('Are you sure you want to close?');
                if (!agree) { close = 0; }
        }
        if (close == 1) {
                $('#modal').addClass("zoomOut").removeClass("zoomIn");
                $('#modalback').css("display", "none");
                $('#modal').css("visibilty", "hidden");
                $('#modal-close').css("visibility", "hidden");
                $('#modal-close').css("display", "none");
                $('#modal2').addClass("zoomOut").removeClass("zoomIn");
                $('#modal2').css("visibilty", "hidden");
                if (stopscroll == '1') { bodyscroll(); }
                setTimeout('hideModalLayer();', 500);
                setTimeout('hideModalLayer2();', 500);
                $('#messages_editor').css("display", "none");
        }
        $('#modal').removeClass("modalbig");
        $('#modal2').removeClass("modalbig");
        $('#modal').removeClass("modalhuge");
        $('#modal2').removeClass("modalhuge");
        $('#modalx').removeClass("modalxfloat");
        $('#modalinner').removeClass("modal-inner-nopadding");
        var modalopena = modalopen.split(":");
        if (modalopena[0] == "headcuration") {
                urlupdate('/headcuration/' + modalopena[2]);
        }
        modalopen = '';
        $('#modalinner').html('');
}

function closeModal2() {
        var close = 1;
        if (document.getElementById('areyousure') != null) {
                var agree = confirm('Are you sure you want to close?');
                if (!agree) { close = 0; }
        }
        if (close == 1) {
                $('#modal2').addClass("zoomOut").removeClass("zoomIn");
                $('#modal2').css("visibilty", "hidden");
                setTimeout('hideModalLayer2();', 500);
        }
        $('#modal2').removeClass("modalbig");
        $('#modal2').removeClass("modalhuge");
        modalopen = '';
}


function editObject(id) {
        if (document.getElementById('editbutton-' + id).innerHTML == 'Edit') {
                sortable('#photos-feed', 'disable');
                document.getElementById('editor-' + id).contentEditable = 'true';
                document.getElementById('editbutton-' + id).innerHTML = 'Save';


        } else {
                var text = document.getElementById('editor-' + id).innerHTML;

                $.ajax({
                        type: "POST",
                        url: me + "/backend/saveobject.php",
                        data: { id: document.getElementById('exhibition_id').value, object_id: id, text: text },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                sortable('#photos-feed');
                                                sortable('#photos-feed', 'enable');
                                                document.getElementById('editbutton-' + id).innerHTML = 'Edit';
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }

        firstlabel();
}

function addObject(type, after) {

        $.ajax({
                type: "POST",
                url: me + "/backend/addobject.php",
                data: { id: document.getElementById('exhibition_id').value, type: type, after: after },
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var object_id = $(this).find('object_id').text();
                                var rand = object_id;
                                if (status == 'OK') {

                                        var addobject = '<div class="exhib-editor-1-addobjects draghide"><span class="button2 grey small" onclick="$(\'#drag-' + rand + '\').remove();">Delete</span> <span class="button2 blue small" onclick="editObject(\'' + rand + '\');" id="editbutton-' + rand + '">Save</span> <span class="button2 yellow small reorderbutton" onclick="reorder(\'' + rand + '\');" id="reorderbutton-' + rand + '">Re-order</span> <span class="button2 jade small" onclick="modal(\'addobject:drag-' + rand + '\');">Add object</span></div>';

                                        if (type == '1') {
                                                var objecthtml = '<div class="drag" id="drag-' + rand + '"><div class="header" id="editor-' + rand + '" contenteditable="true">Edit me</div>' + addobject + '</div>';
                                        }

                                        if (type == '2') {
                                                var objecthtml = '<div class="drag" id="drag-' + rand + '"><div class="megatext" id="editor-' + rand + '" contenteditable="true"><b>Edit here.</b> And edit this aswell.</div>' + addobject + '</div>';
                                        }

                                        if (type == '3') {
                                                var objecthtml = '<div class="drag" id="drag-' + rand + '"><div class="textobject" id="editor-' + rand + '" contenteditable="true">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas iaculis, leo nec pharetra egestas, purus nisi venenatis nisi, ac ullamcorper ex est sit amet odio. Vivamus lobortis magna ut auctor lobortis. Maecenas fermentum ante vitae tellus pellentesque, ut tristique mauris aliquam. Curabitur enim lectus, accumsan vel massa vel, gravida ultrices magna. Aliquam in efficitur orci. Etiam suscipit est a orci sollicitudin, at sagittis velit pellentesque. Nullam venenatis efficitur erat, eget consequat erat convallis et. Mauris consectetur, massa in fringilla molestie, magna urna suscipit magna, non euismod dolor dui non urna.</div>' + addobject + '</div>';
                                        }

                                        objecthtml += "<div onclick=\"doMove('after','" + rand + "');\" class=\"movehere\">Click to move it here</div>";

                                        $(objecthtml).insertAfter("#" + after);
                                        closeModal();
                                        $('#drag-' + rand).focus();

                                } else {
                                        alert(status);
                                }
                        });
                }
        });

        firstlabel();
}

function hideModalLayer() {
        $('#modal').css("z-index", "-50");
}

function hideModalLayer2() {
        $('#modal2').css("z-index", "-50");
}


function processLogin() {
        var name = auth_name.split(" ");
        if (auth != '') {
                document.getElementById('rightlinks-notsignedin').style.display = 'none';
                document.getElementById('rightlinks-signedin').style.display = 'inline';
                if (document.getElementById('thumbzone-signedin') != null) {
                        document.getElementById('thumbzone-signedin').style.display = 'block';
                        document.getElementById('thumbzone-notsignedin').style.display = 'none';
                }
                document.getElementById('mainmenu_items_notsignedin').style.display = 'none';
                document.getElementById('mainmenu_items_signedin').style.display = 'block';
                if (auth_img != '') {
                        document.getElementById('auth_img_span').style.display = 'inline';
                        document.getElementById('auth_img').src = 'https://gallery.1x.com/images/profile/' + auth_img + '-square.jpg';
                        document.getElementById('auth_img_span2').style.display = 'inline';
                        document.getElementById('auth_img2').src = 'https://gallery.1x.com/images/profile/' + auth_img + '-square.jpg';
                } else {
                        document.getElementById('auth_img_span').style.display = 'none';
                        document.getElementById('auth_img').src = '';
                        document.getElementById('auth_img_span2').style.display = 'none';
                        document.getElementById('auth_img2').src = '';
                }
                document.getElementById('auth_name').innerHTML = name[0];
                document.getElementById('auth_name2').innerHTML = name[0];
        } else {
                document.getElementById('rightlinks-notsignedin').style.display = 'inline';
                document.getElementById('rightlinks-signedin').style.display = 'none';
                if (document.getElementById('thumbzone-signedin') != null) {
                        document.getElementById('thumbzone-signedin').style.display = 'none';
                        document.getElementById('thumbzone-notsignedin').style.display = 'block';
                }
                document.getElementById('mainmenu_items_notsignedin').style.display = 'block';
                document.getElementById('mainmenu_items_signedin').style.display = 'none';
                document.getElementById('auth_img_span').style.display = 'none';
                document.getElementById('auth_img').src = '';
                document.getElementById('auth_name').innerHTML = '';
        }
}

function createexhibition() {
        if (document.getElementById('create_exhibition_name').value != '' && document.getElementById('create_exhibition_photos').value != '') {
                $.ajax({
                        type: "POST",
                        url: me + "/backend/createexhibition.php",
                        data: { name: document.getElementById('create_exhibition_name').value, photos: document.getElementById('create_exhibition_photos').value },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var id = $(this).find('id').text();
                                        var url = $(this).find('url').text();
                                        if (status == 'OK') {
                                                closeModal();
                                                location.href = url;
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        } else {
                alert('Failed to create exhibition - name or photos missing!');
        }
}

function addImagesExhib() {
        if (parseInt(document.getElementById('exhibition_id').value) > 0) {
                var direction = 'asc';
                if (document.getElementById('add_images_desc').checked == 1) { direction = 'desc'; }
                $.ajax({
                        type: "POST",
                        url: me + "/backend/addphotosexhib.php",
                        data: { id: document.getElementById('exhibition_id').value, photos: document.getElementById('create_exhibition_photos').value, direction: direction },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                closeModal();
                                                location.href = location.href;
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}

function like(id) {
        if (auth == '') {
                modal('signin', '0');
                resume = 'like:' + id + ':';
        } else {
                if (document.getElementById('likestate-' + id).value == '0') {
                        $('#heart-' + id).removeClass("far"); $('#heart-' + id).addClass("fas");
                        if (document.getElementById('heart2-' + id) != null) {
                                $('#heart2-' + id).removeClass("far"); $('#heart2-' + id).addClass("fas");
                                document.getElementById('likecount-' + id).innerHTML = parseInt(document.getElementById('likecount-' + id).innerHTML) + 1;
                        }
                        document.getElementById('likestate-' + id).value = '1';
                } else {
                        if (document.getElementById('likestate-' + id).value == '1') {
                                $('#heart-' + id).removeClass("fas"); $('#heart-' + id).addClass("far");
                                if (document.getElementById('heart2-' + id) != null) {
                                        $('#heart2-' + id).removeClass("fas"); $('#heart2-' + id).addClass("far");
                                        document.getElementById('likecount-' + id).innerHTML = parseInt(document.getElementById('likecount-' + id).innerHTML) - 1;
                                }
                                document.getElementById('likestate-' + id).value = '0';
                        }
                }

                $.ajax({
                        type: "POST",
                        url: me + "/backend/like.php",
                        data: { id: id },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var state = $(this).find('state').text();
                                        if (status == 'OK') {
                                                if (state == '1') {
                                                        $('#heart-' + id).removeClass("far"); $('#heart-' + id).addClass("fas");
                                                        document.getElementById('likestate-' + id).value = '1';
                                                } else {
                                                        if (state == '0') {
                                                                $('#heart-' + id).removeClass("fas"); $('#heart-' + id).addClass("far");
                                                                document.getElementById('likestate-' + id).value = '0';
                                                        }
                                                }
                                        } else {
                                                alert(status);
                                                if (state == '1') {
                                                        $('#heart-' + id).removeClass("far"); $('#heart-' + id).addClass("fas");
                                                        document.getElementById('likestate-' + id).value = '1';
                                                } else {
                                                        if (state == '0') {
                                                                $('#heart-' + id).removeClass("fas"); $('#heart-' + id).addClass("far");
                                                                document.getElementById('likestate-' + id).value = '0';
                                                        }
                                                }

                                        }
                                });
                        }
                });



        }
}

function login() {
        var auth_email = document.getElementById('login_email').value;
        var auth_password = document.getElementById('login_password').value;

        if (auth_email != '' && auth_password != '') {
                document.getElementById('modalblock').style.display = 'block';
                $.ajax({
                        type: "POST",
                        url: me + "/backend/login.php",
                        data: { email: auth_email, password: auth_password },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var a_id = $(this).find('id').text();
                                        var a_name = $(this).find('name').text();
                                        var a_img = $(this).find('img').text();
                                        if (status == 'OK') {
                                                document.getElementById('modalblock').style.display = 'none';
                                                auth = a_id;
                                                auth_name = a_name;
                                                auth_img = a_img;
                                                processLogin();
                                                var login_resume = document.getElementById('login_resume').value;
                                                closeModal();
                                                if (resume != '') {
                                                        var resumea = resume.split(":");
                                                        if (resumea[0] == "like" && parseInt(resumea[1]) > 0) {
                                                                like(resumea[1]);
                                                        }
                                                        resume = '';
                                                }
                                                if (app == "curate") {
                                                        location.href = location.href;
                                                }
                                                if (app == "pro") {
                                                        location.href = location.href;
                                                }
                                                if (login_resume != '') {
                                                        setTimeout('modal(\'' + login_resume + '\',\'0\');', 1000);
                                                }
                                                if (app == 'frontnonmember') {
                                                        location.href = '/';
                                                }
                                        } else {
                                                alert(status);
                                                document.getElementById('modalblock').style.display = 'none';
                                        }
                                });
                        }
                });
        } else {
                alert('Fill in both e-mail and password');
        }
}

function signout() {
        document.getElementById('loader').style.display = 'block';
        $.ajax({
                type: "POST",
                url: me + "/backend/signout.php",
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        auth = '';
                                        auth_name = '';
                                        auth_img = '';
                                        processLogin();
                                        document.getElementById('loader').style.display = 'none';
                                        location.href = '/';
                                } else {
                                        alert(status);
                                        document.getElementById('loader').style.display = 'none';
                                }
                        });
                }
        });

}

function controlcenter(what, doclear) {

        if (typeof (window.innerWidth) == 'number') {
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
        }

        $('#messages_editor').css("display", "none");

        if (!doclear) { doclear = 0; }
        if (cc != '') {
                $('#modal-inner-block1-link-' + cc).removeClass("modal-inner-block1-link-active");
                $('#modal-inner-block1-link-' + cc).addClass("modal-inner-block1-link");
                cc = '';
        }
        if (document.getElementById('cc-new-' + what) != null) {
                setTimeout('$(\'#cc-new-' + what + '\').remove();', 1000);
        }
        $('#modal-inner-block1-link-' + what).removeClass("modal-inner-block1-link");
        $('#modal-inner-block1-link-' + what).addClass("modal-inner-block1-link-active");
        if (doclear == 0) { $('#cc-inner').html('<table class="modal-load" width="100%" height="100%" border="0" cellpadding="0" cellspacing="0"><tr><td class="modal-load-td"><center><div class="lds-ring"><div></div><div></div><div></div><div></div></div></center></td></tr></table>'); }
        cc = what;
        $.ajax({
                type: "GET",
                url: me + "/backend/controlcenter.php?id=" + what,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var data = $(this).find('data').text();
                                if (status == 'OK') {
                                        $('#cc-inner').html(data);
                                        if (what == 'messages') {
                                                var basewidth = parseInt($('#modal-inner-block2').innerWidth()) - 300;
                                                if (myHeight < myWidth) {
                                                        $('#messages_reader').css("width", basewidth + "px");
                                                        $('#messages_editor').css("width", basewidth + "px");
                                                }
                                        }

                                        if (what == 'messages' || what == 'notifications') {
                                                clearTimeout(nottimer);
                                                nottimer = setTimeout('notCount();', 600);
                                        }

                                        if (document.getElementById('profilepicupload') != null) {
                                                $("#profilepicupload").dropzone({ url: "/backend/profilepicupload.php", paramName: "file", createImageThumbnails: false, previewTemplate: '', success: function (file, response) { profilepicdone(file.name, response); }, addedfile: function (file) { nloader('Uploading...'); }, thumbnail: function (file, dataUrl) { }, uploadprogress: function (file, progress, bytesSent) { nloader('Uploading... ' + progress + '% done'); }, accept: function (file, done) { done(); } });
                                        }
                                }
                        });
                }
        });
}

function profilepicdone(filename, response) {
        if (response) {
                var obj = JSON.parse(response);
                if (obj["status"] == "OK") {
                        location.href = '/settings';
                        mixpanel.track('Uploaded a profile pic');
                } else {
                        error(obj["error"]);
                }
        }
}

function magazinepicdone(filename, response) {
        if (response) {
                var obj = JSON.parse(response);
                if (obj["status"] == "OK") {
                        nloaderstop();
                        var quotehtml = '<div class="magazine-image-big"><img src="' + obj["url"] + '"></div>';
                        tinymce.get('magazine-editor').execCommand('mceInsertContent', false, quotehtml);
                        closeModal();
                } else {
                        error(obj["error"]);
                }
        }
}

function reuploaddone(filename, response) {
        if (response) {
                var obj = JSON.parse(response);
                if (obj["status"] == "OK") {
                        nloaderstop();
                        modal('reupload:' + document.getElementById('reupload-id').value + ':', '', '');
                } else {
                        error(obj["error"]);
                }
        }
}

function profilepicdone2(filename, response) {
        if (response) {
                var obj = JSON.parse(response);
                if (obj["status"] == "OK") {
                        modal('editprofile', '1');
                } else {
                        error(obj["error"]);
                }
        }
}

function reuploadagain() {
        if (document.getElementById('reupload-id') != null) {
                $.ajax({
                        type: "GET",
                        url: "/backend/reuploadagain.php?id=" + document.getElementById('reupload-id').value,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                modal('reupload:' + document.getElementById('reupload-id').value + ':', '', '');
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}

function signupStep1() {
        var signup_email = document.getElementById('signup_email').value;
        var signup_pw = document.getElementById('signup_password').value;
        var invite_code = '';

        if (document.getElementById('invite_code') != null) {
                invite_code = document.getElementById('invite_code').value;
        }

        if (signup_pw.length > 7) {
                grecaptcha.ready(function () {
                        grecaptcha.execute('6Lc4kd4ZAAAAAISalhrF3nyrdXXbXMfzwmno8F68', { action: 'submit' }).then(function (token) {

                                $.ajax({
                                        type: "POST",
                                        url: "/backend/authc.php",
                                        data: { step: "1", email: signup_email, password: signup_pw, token: token },
                                        dataType: "xml",
                                        success: function (xml) {
                                                $(xml).find('root').each(function () {
                                                        var status = $(this).find('status').text();
                                                        if (status == 'OK') {
                                                                modal('signup:2:', '1');
                                                        } else {
                                                                alert(status);
                                                        }
                                                });
                                        }
                                });

                        });
                });
        } else {
                alert('Your password must be at least 8 characters long');
        }
}

function signupStep2() {
        var signup_name = document.getElementById('signup_name').value;
        if (signup_name != '') {
                $.ajax({
                        type: "POST",
                        url: "/backend/authc.php",
                        data: { step: "2", name: signup_name },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                modal('signup:3:', '1');
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        } else {
                alert('Please enter your name');
        }
}

function signupStep3() {
        var signup_about = document.getElementById('signup_about').value;
        if (signup_about != '') {
                $.ajax({
                        type: "POST",
                        url: "/backend/authc.php",
                        data: { step: "3", about: signup_about },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                modal('signup:4:', '1');
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        } else {
                alert('Please write a short description about yourself - you can write in your native language');
        }
}

function signupStep4() {
        var signup_username = document.getElementById('signup_username').value;
        if (signup_username != '') {
                $.ajax({
                        type: "POST",
                        url: "/backend/authc.php",
                        data: { step: "4", username: signup_username },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                modal('signup:5:', '1');
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        } else {
                alert('Please select a username');
        }
}

function signupStep5() {
        var signup_country = document.getElementById('signup_country').value;

        var invite_code = '';

        if (document.getElementById('invite_code') != null) {
                invite_code = document.getElementById('invite_code').value;
        }

        if (signup_country != '') {
                $.ajax({
                        type: "POST",
                        url: "/backend/authc.php",
                        data: { step: "5", country: signup_country, invite_code: invite_code },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                modal('signup:6:', '1');
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        } else {
                alert('Please select a country');
        }
}

function modal(what, stopscroll, where) {

        stopscroll = '1';

        if (!where) {
                where = '';
        }

        var whata = what.split(":");

        if (whata[0] == 'addimages' || whata[0] == "createexhibition" && whata[1] == "2" || whata[0] == 'uploader' || whata[0] == 'editphoto' || whata[0] == 'cc' || whata[0] == "search" || whata[0] == "sendmsg" || whata[0] == "overview" || whata[0] == "directory" || whata[0] == "tagger" || whata[0] == "tag" || whata[0] == "messenger" || whata[0] == "visaforumbild" || whata[0] == "purpose" || whata[0] == "guide" || whata[0] == "updated-agreement") {
                $('#modal' + where).addClass("modalbig");
        }

        if (whata[0] == 'headcuration' || whata[0] == 'tagging') {
                if (document.getElementById('lm_active') == null) {
                        $('#all_hiddens').prepend('<input type="hidden" id="lm_active" value="0">');
                }
                $('#modal' + where).addClass("modalbig");
                $('#modal' + where).addClass("modalhuge");
                $('#modalinner').addClass("modal-inner-nopadding");
                $('#modalx').addClass("modalxfloat");
                if (whata[0] == 'headcuration') { urlupdate('/headcuration/' + whata[2] + '/' + whata[1]); }
        }

        if (stopscroll == '1') { bodystopscroll(); }
        $('#modal' + where).addClass("zoomIn").removeClass("zoomOut");
        $('#modalback').css("display", "block");
        $('#modal' + where).css("visibility", "visible");
        $('#modal-close').css("visibility", "visible");
        $('#modal-close').css("display", "block");
        $('#modal' + where).css("z-index", "50");
        if (where == '2') { $('#modal' + where).css("z-index", "51"); }

        if (retainmodal == '' || retainmodal != what) {
                retainmodal = '';
                $('#modalinner' + where).html('<table class="modal-load" width="100%" height="100%" border="0" cellpadding="0" cellspacing="0"><tr><td class="modal-load-td"><center><div class="lds-ring"><div></div><div></div><div></div><div></div></div></center></td></tr></table>');

                $.ajax({
                        type: "GET",
                        url: me + "/backend/modal.php?id=" + what + "&deviceType=" + device_Type,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var data = $(this).find('data').text();
                                        var adata1 = $(this).find('adata1').text();
                                        var adata2 = $(this).find('adata2').text();
                                        var extradata = $(this).find('extradata').text();
                                        if (status == 'OK') {
                                                if (whata[0] == "tag") { data = '<div id="modal_data_inner" style="display: none;">' + data + '</div>'; }
                                                modalopen = what;
                                                $('#modalinner' + where).html(data);
                                                if (what == 'messenger') {
                                                        $('#modalinner').addClass("modal-inner-messenger");
                                                        $('#rightbubble-message').removeClass("rightbubble-on");
                                                        $('#rightbubble-message2').removeClass("rightbubble-on");
                                                } else {
                                                        $('#modalinner').removeClass("modal-inner-messenger");
                                                }
                                                $('#modal_data_inner').fadeIn();

                                                if (document.getElementById('tagging_undo') != null) {
                                                        if (parseInt(tagging_undo_picid) > 0 && tagging_undo_phaseid == whata[2]) {
                                                                $('#tagging_undo').css("display", "inline");
                                                        }
                                                }

                                                if (document.getElementById('magazinepicupload') != null) {
                                                        $("#magazinepicupload").dropzone({ url: "/backend/magazinepicupload.php", paramName: "file", createImageThumbnails: false, previewTemplate: '', success: function (file, response) { magazinepicdone(file.name, response); }, addedfile: function (file) { }, thumbnail: function (file, dataUrl) { }, uploadprogress: function (file, progress, bytesSent) { nloader('Uploading... ' + progress + '% done'); }, accept: function (file, done) { done(); } });
                                                }

                                                if (document.getElementById('profilepicupload2') != null) {
                                                        $("#profilepicupload2").dropzone({ url: "/backend/profilepicupload.php", paramName: "file", createImageThumbnails: false, previewTemplate: '', success: function (file, response) { profilepicdone2(file.name, response); }, addedfile: function (file) { }, thumbnail: function (file, dataUrl) { }, uploadprogress: function (file, progress, bytesSent) { }, accept: function (file, done) { done(); } });
                                                }
                                                if (whata[0] == "guide") {
                                                        var guidedelay = 0;
                                                        var guidedelay_add = 500;
                                                        if (document.getElementById('guide_01') != null) {
                                                                $('#guide_01').animate({ opacity: "1" }, 1000);
                                                                guidedelay = guidedelay + guidedelay_add;
                                                        }
                                                        if (document.getElementById('guide_02') != null) {
                                                                setTimeout('$(\'#guide_02\').animate({ opacity: "1" }, 1000);', guidedelay);
                                                                guidedelay = guidedelay + guidedelay_add;
                                                        }
                                                        if (document.getElementById('guide_03') != null) {
                                                                setTimeout('$(\'#guide_03\').animate({ opacity: "1" }, 1000);', guidedelay);
                                                                guidedelay = guidedelay + guidedelay_add;
                                                        }
                                                        if (document.getElementById('guide_04') != null) {
                                                                setTimeout('$(\'#guide_04\').animate({ opacity: "1" }, 1000);', guidedelay);
                                                                guidedelay = guidedelay + guidedelay_add;
                                                        }
                                                        if (document.getElementById('guide_05') != null) {
                                                                setTimeout('$(\'#guide_05\').animate({ opacity: "1" }, 1000);', guidedelay);
                                                                guidedelay = guidedelay + guidedelay_add;
                                                        }
                                                        if (document.getElementById('guide_06') != null) {
                                                                setTimeout('$(\'#guide_06\').animate({ opacity: "1" }, 1000);', guidedelay);
                                                                guidedelay = guidedelay + guidedelay_add;
                                                        }
                                                        if (document.getElementById('guide_07') != null) {
                                                                setTimeout('$(\'#guide_07\').animate({ opacity: "1" }, 1000);', guidedelay);
                                                                guidedelay = guidedelay + guidedelay_add;
                                                        }
                                                        if (document.getElementById('guide_08') != null) {
                                                                setTimeout('$(\'#guide_08\').animate({ opacity: "1" }, 1000);', guidedelay);
                                                                guidedelay = guidedelay + guidedelay_add;
                                                        }
                                                }

                                                if (whata[0] == "signin") {
                                                }
                                                if (whata[0] == "search") {
                                                        retainmodal = 'search';
                                                }
                                                if (whata[0] == 'uploader') {
                                                        var uploaderjs = new qq.FileUploader({
                                                                element: document.getElementById('file-uploader'),
                                                                action: '/backend/upload.php',
                                                                onComplete: function (id, fileName, responseJSON) { if (!responseJSON["success"]) { alert(responseJSON["error"]); modal('uploader', '1'); } },
                                                                debug: false
                                                        });
                                                }
                                                if (whata[0] == "overview") {
                                                        retainmodal = 'overview';
                                                        overviewLoad();
                                                }
                                                if (whata[0] == "editmsg") {
                                                        document.getElementById('editforum-text').value = document.getElementById('rawtext_' + whata[1]).innerHTML;
                                                        document.getElementById('edit_msg_id').value = whata[1];
                                                        document.getElementById('edit_topic_id').value = whata[2];
                                                        if (whata[3] == '1') {
                                                                document.getElementById('editforum-name-section').style.display = 'block';
                                                                document.getElementById('editforum-name').value = document.getElementById('topicname').value;
                                                        } else {
                                                                document.getElementById('editforum-name-section').style.display = 'none';
                                                        }

                                                }
                                                if (whata[0] == "sendmsg") {
                                                        if (document.getElementById('msg_send_to') == null) {
                                                                document.getElementById('message_tofind').focus();
                                                        }
                                                        autosize($('#message-text'));
                                                }
                                                if (whata[0] == "cc") {
                                                        cc = '';
                                                        controlcenter(whata[1]);
                                                        if (document.getElementById('modal-inner-block2') != null) {
                                                                document.getElementById('modal-inner-block2').style.height = $('#modal').innerHeight() - 293 + 'px';
                                                        }
                                                }

                                                if (document.getElementById('uploader-forum') != null) {
                                                        $("#uploader-forum").dropzone({ url: "/backend/newforum_uploadforum.php?topic_id=" + document.getElementById('upload_topic_id').value, paramName: "file", createImageThumbnails: false, previewTemplate: '', success: function (file, response) { uploaddoneforum(file.name, response); }, addedfile: function (file) { uploadaddforum(file.name, file.type); }, thumbnail: function (file, dataUrl) { }, uploadprogress: function (file, progress, bytesSent) { uploadprogressforum(file.name, progress, bytesSent); }, accept: function (file, done) { done(); } });
                                                }

                                                if (document.getElementById('reuploadbutton') != null) {
                                                        var reuploadid = document.getElementById('reupload-id').value;
                                                        $("#reuploadbutton").dropzone({ url: "/backend/reupload.php?id=" + reuploadid, paramName: "file", createImageThumbnails: false, timeout: 1000000, maxFilesize: 500, previewTemplate: '', success: function (file, response) { reuploaddone(file.name, response); }, addedfile: function (file) { nloader('Your file is uploading... Please wait...'); }, thumbnail: function (file, dataUrl) { }, uploadprogress: function (file, progress, bytesSent) { nloadermsg('Uploaded ' + progress + '%'); }, accept: function (file, done) { done(); } });
                                                }

                                                if (document.getElementById('replace-button') != null) {
                                                        var reuploadid = document.getElementById('reupload-id').value;
                                                        //$("#replace-button").dropzone({ url: "/backend/replaceprintfile.php?id="+reuploadid, paramName: "file", createImageThumbnails: false, timeout: 1000000, maxFilesize: 500, previewTemplate: '', success: function(file,response) { replaceprintfiledone(file.name,response); }, addedfile: function(file) { replaceprintfilestarted(); }, thumbnail: function(file, dataUrl) { }, uploadprogress: function(file, progress, bytesSent) { replaceprintfileprogress(file.name,progress); }, accept: function(file, done) { done(); } });
                                                        $("#replace-button").dropzone({ timeout: 1000000, maxFilesize: 1000, url: "/backend/replaceprintfile.php?id=" + reuploadid, paramName: "file", createImageThumbnails: false, previewTemplate: '', success: function (file, response) { replaceprintfiledone(file, response); }, addedfile: function (file) { replaceprintfilestarted(file); }, thumbnail: function (file, dataUrl) { }, uploadprogress: function (file, progress, bytesSent) { replaceprintfileprogress(file, progress, bytesSent); }, accept: function (file, done) { done(); } });
                                                }

                                                if (whata[0] == "editphoto") {
                                                        if (document.getElementById('statcircle_1') != null) {
                                                                circlePosition('1', '0');
                                                                circlePosition('2', '0');
                                                                circlePosition('3', '0');
                                                                circlePosition('4', '0');
                                                                setTimeout('showCircle(\'1\');', 200);
                                                                setTimeout('showCircle(\'2\');', 400);
                                                                setTimeout('showCircle(\'3\');', 600);
                                                                setTimeout('showCircle(\'4\');', 800);
                                                                setTimeout('circlePosition(\'1\',document.getElementById(\'stat_1\').value);', 500);
                                                                setTimeout('circlePosition(\'2\',document.getElementById(\'stat_2\').value);', 700);
                                                                setTimeout('circlePosition(\'3\',document.getElementById(\'stat_3\').value);', 900);
                                                                setTimeout('circlePosition(\'4\',document.getElementById(\'stat_4\').value);', 1100);
                                                        }
                                                        if (document.getElementById('aiscore') != null) {
                                                                var opts = {
                                                                        colorStart: "#E42256",
                                                                        colorStop: void 0,
                                                                        gradientType: 0,
                                                                        strokeColor: "#ffffff",
                                                                        generateGradient: true,
                                                                        percentColors: [[0.0, "#E42256"], [0.5, "#FEC84D"], [0.6, "#aec110"], [0.9, "#10c191"]],
                                                                        staticZones: [
                                                                                { strokeStyle: "#E42256", min: 0, max: 25 },
                                                                                { strokeStyle: "#FEC84D", min: 25, max: 50 },
                                                                                { strokeStyle: "#aec110", min: 50, max: 75 },
                                                                                { strokeStyle: "#10c191", min: 75, max: 100 }
                                                                        ]
                                                                };
                                                                var target = document.getElementById('aiscore');
                                                                var gauge = new Gauge(target).setOptions(opts);

                                                                gauge.maxValue = 100;
                                                                gauge.setMinValue(0);
                                                                gauge.set(document.getElementById('aiscore_value').value);

                                                        }


                                                        if (document.getElementById('chartdiv1') != null) {


                                                                am4core.ready(function () {

                                                                        am4core.useTheme(am4themes_spiritedaway);
                                                                        var chart = am4core.create("chartdiv1", am4charts.PieChart);
                                                                        var pieSeries = chart.series.push(new am4charts.PieSeries());
                                                                        pieSeries.dataFields.value = "percent";
                                                                        pieSeries.dataFields.category = "category";
                                                                        chart.innerRadius = am4core.percent(30);
                                                                        pieSeries.slices.template.stroke = am4core.color("#fff");
                                                                        pieSeries.slices.template.strokeWidth = 2;
                                                                        pieSeries.slices.template.strokeOpacity = 1;
                                                                        pieSeries.slices.template
                                                                                .cursorOverStyle = [
                                                                                        {
                                                                                                "property": "cursor",
                                                                                                "value": "pointer"
                                                                                        }
                                                                                ];
                                                                        pieSeries.alignLabels = false;
                                                                        pieSeries.labels.template.bent = true;
                                                                        pieSeries.labels.template.radius = 3;
                                                                        pieSeries.labels.template.padding(0, 0, 0, 0);
                                                                        pieSeries.ticks.template.disabled = true;
                                                                        pieSeries.slices.template.tooltipText = "{category} {value}%";
                                                                        var shadow = pieSeries.slices.template.filters.push(new am4core.DropShadowFilter);
                                                                        shadow.opacity = 0;
                                                                        var hoverState = pieSeries.slices.template.states.getKey("hover"); // normally we have to create the hover state, in this case it already exists
                                                                        var hoverShadow = hoverState.filters.push(new am4core.DropShadowFilter);
                                                                        hoverShadow.opacity = 0.7;
                                                                        hoverShadow.blur = 5;
                                                                        chart.legend = new am4charts.Legend();
                                                                        if (darkmode == 1) {
                                                                                pieSeries.legendSettings.labelText = "Series: [bold #fff]{name}[/]";
                                                                        }
                                                                        chart.data = [{}, {}, {}, {}, {}, {}]
                                                                        adata1s = adata1.split(":");
                                                                        if (adata1s[0] && parseInt(adata1s[1]) > 0) { chart.data[0]["category"] = adata1s[0]; chart.data[0]["percent"] = adata1s[1]; }
                                                                        if (adata1s[2] && parseInt(adata1s[3]) > 0) { chart.data[1]["category"] = adata1s[2]; chart.data[1]["percent"] = adata1s[3]; }
                                                                        if (adata1s[4] && parseInt(adata1s[5]) > 0) { chart.data[2]["category"] = adata1s[4]; chart.data[2]["percent"] = adata1s[5]; }
                                                                        if (adata1s[6] && parseInt(adata1s[7]) > 0) { chart.data[3]["category"] = adata1s[6]; chart.data[3]["percent"] = adata1s[7]; }
                                                                        if (adata1s[8] && parseInt(adata1s[9]) > 0) { chart.data[4]["category"] = adata1s[8]; chart.data[4]["percent"] = adata1s[9]; }
                                                                        if (adata1s[10] && parseInt(adata1s[11]) > 0) { chart.data[5]["category"] = adata1s[10]; chart.data[5]["percent"] = adata1s[11]; }
                                                                        if (adata1s[12] && parseInt(adata1s[13]) > 0) { chart.data[6]["category"] = adata1s[12]; chart.data[6]["percent"] = adata1s[13]; }


                                                                        am4core.useTheme(am4themes_material);
                                                                        var chart2 = am4core.create("chartdiv2", am4charts.PieChart);
                                                                        var pieSeries2 = chart2.series.push(new am4charts.PieSeries());
                                                                        pieSeries2.dataFields.value = "percent";
                                                                        pieSeries2.dataFields.category = "category";
                                                                        chart2.innerRadius = am4core.percent(30);
                                                                        pieSeries2.slices.template.stroke = am4core.color("#fff");
                                                                        pieSeries2.slices.template.strokeWidth = 2;
                                                                        pieSeries2.slices.template.strokeOpacity = 1;
                                                                        pieSeries2.slices.template
                                                                                .cursorOverStyle = [
                                                                                        {
                                                                                                "property": "cursor",
                                                                                                "value": "pointer"
                                                                                        }
                                                                                ];
                                                                        pieSeries2.alignLabels = false;
                                                                        pieSeries2.labels.template.bent = true;
                                                                        pieSeries2.labels.template.radius = 3;
                                                                        pieSeries2.labels.template.padding(0, 0, 0, 0);
                                                                        pieSeries2.ticks.template.disabled = true;
                                                                        pieSeries2.slices.template.tooltipText = "{category} {value}%";
                                                                        var shadow2 = pieSeries.slices.template.filters.push(new am4core.DropShadowFilter);
                                                                        shadow2.opacity = 0;
                                                                        var hoverState2 = pieSeries2.slices.template.states.getKey("hover"); // normally we have to create the hover state, in this case it already exists
                                                                        var hoverShadow2 = hoverState2.filters.push(new am4core.DropShadowFilter);
                                                                        hoverShadow2.opacity = 0.7;
                                                                        hoverShadow2.blur = 5;
                                                                        chart2.legend = new am4charts.Legend();
                                                                        if (darkmode == 1) {
                                                                                pieSeries2.legendSettings.labelText = "Series: [bold #fff]{name}[/]";
                                                                        }
                                                                        chart2.data = [{}, {}, {}, {}, {}, {}]
                                                                        adata2s = adata2.split(":");
                                                                        if (adata2s[0] && parseInt(adata2s[1]) > 0) { chart2.data[0]["category"] = adata2s[0]; chart2.data[0]["percent"] = adata2s[1]; }
                                                                        if (adata2s[2] && parseInt(adata2s[3]) > 0) { chart2.data[1]["category"] = adata2s[2]; chart2.data[1]["percent"] = adata2s[3]; }
                                                                        if (adata2s[4] && parseInt(adata2s[5]) > 0) { chart2.data[2]["category"] = adata2s[4]; chart2.data[2]["percent"] = adata2s[5]; }
                                                                        if (adata2s[6] && parseInt(adata2s[7]) > 0) { chart2.data[3]["category"] = adata2s[6]; chart2.data[3]["percent"] = adata1s[7]; }
                                                                        if (adata2s[8] && parseInt(adata2s[9]) > 0) { chart2.data[4]["category"] = adata2s[8]; chart2.data[4]["percent"] = adata1s[9]; }
                                                                        if (adata2s[10] && parseInt(adata2s[11]) > 0) { chart2.data[5]["category"] = adata2s[10]; chart2.data[5]["percent"] = adata1s[11]; }
                                                                        if (adata2s[12] && parseInt(adata2s[13]) > 0) { chart2.data[6]["category"] = adata2s[12]; chart2.data[6]["percent"] = adata1s[13]; }


                                                                }); // end am4core.ready()


                                                        }
                                                }
                                        } else {
                                                if (status != "DONE") {
                                                        alert(status);
                                                        closeModal();
                                                } else {
                                                        if (extradata == '0') {
                                                                closeModal();
                                                        } else {
                                                                if (extradata != '' && extradata != '2' && extradata != '12') {
                                                                        if (extradata == '3') {
                                                                                centermessage('Changing to Phase 2', 2000);
                                                                                modal('tagging:metadata:4:');
                                                                        }
                                                                        if (extradata == '4') {
                                                                                centermessage('Changing to Phase 3', 2000);
                                                                                modal('tagging:metadata:12:');
                                                                        }
                                                                        if (extradata == '7') {
                                                                                centermessage('Changing to Phase 5', 2000);
                                                                                modal('tagging:keyword:14:');
                                                                        }
                                                                        if (extradata == '14') {
                                                                                centermessage('Changing to Phase 6', 2000);
                                                                                modal('tagging:keyword:2:');
                                                                        }
                                                                } else {
                                                                        closeModal();
                                                                }
                                                        }
                                                }
                                        }
                                });
                        }
                });


        }

}

function showCircle(circle) {
        $('#statcircle_' + circle).animate({ opacity: 1 }, 1000);
}

function indicateLoadMore() {
        $('#gallery-loadmore').animate({ opacity: 1 }, 1000);
}

var loadmorecustomactive = '0';

function loadmorecustom(what) {
        var yourpositionblock = 0;
        if (what == 'yourposition') {
                if (document.getElementById('toplists-myplace') != null) {
                        scrollto('toplists-myplace', 100);
                        yourpositionblock = 1;
                }
        }

        if (loadmorecustomactive == '0' && yourpositionblock == 0) {
                if (what == 'yourposition') { document.getElementById('loader').style.display = 'block'; }
                loadmorecustomactive = '1';
                if (document.getElementById('lm_custom_enabled') != null) {
                        var lm_custom_enabled = document.getElementById('lm_custom_enabled').value;
                        var lm_custom_mode = document.getElementById('lm_custom_mode').value;
                        var lm_custom_target = document.getElementById('lm_custom_target').value;
                        var lm_custom_target_type = document.getElementById('lm_custom_target_type').value;
                        var lm_custom_perpage = document.getElementById('lm_custom_perpage').value;
                        var lm_custom_from = document.getElementById('lm_custom_from').value;

                        if (lm_custom_enabled == '1') {
                                $.ajax({
                                        type: "GET",
                                        url: me + "/backend/customloadmore.php?mode=" + lm_custom_mode + "&from=" + lm_custom_from + "&perpage=" + lm_custom_perpage,
                                        dataType: "xml",
                                        success: function (xml) {
                                                $(xml).find('root').each(function () {
                                                        var status = $(this).find('status').text();
                                                        var data = $(this).find('data').text();
                                                        var from = $(this).find('from').text();
                                                        var active = $(this).find('active').text();
                                                        if (status == 'OK') {
                                                                if (active != '1') {
                                                                        document.getElementById('lm_custom_enabled').value = '0';
                                                                }
                                                                document.getElementById('lm_custom_from').value = from;
                                                                $('#' + lm_custom_target).append(data);
                                                                loadmorecustomactive = '0';
                                                                if (what == 'yourposition') {
                                                                        if (document.getElementById('toplists-myplace') == null) {
                                                                                loadmorecustom(what);
                                                                        } else {
                                                                                scrollto('toplists-myplace', 100);
                                                                                document.getElementById('loader').style.display = 'none';
                                                                        }
                                                                }
                                                        } else {
                                                                alert(status);
                                                                document.getElementById('lm_custom_enabled').value = '0';
                                                                loadmorecustomactive = '0';
                                                        }
                                                });
                                        }
                                });
                        }
                }
        }
}

function doLoadmoreLooped() {
        clearTimeout(loadmorelooptimer);
        if (document.getElementById('lm_active').value == '1') {
                loadmorelooptimer = setTimeout('doLoadmoreLooped();', 3000);
                doLoadmore();
        }
}

function doLoadmore() {
        var search_q = '';
        var search_active = 0;

        if (document.getElementById('lm_search') != null) {
                search_q = document.getElementById('lm_search').value;
                search_active = 1;
        }

        if (loadmore == '0' && loadmoreblock == '0' && search_active == 0 || loadmore == '0' && loadmoreblock == '0' && search_active == 1 && search_q != '') {
                if (document.getElementById('lm_active').value == '1') {
                        loadmore = '1';
                        loadmoreindicator = setTimeout('indicateLoadMore();', 500);
                        var lm_mode_o = document.getElementById('lm_mode').value;
                        var lm_mode = lm_mode_o.split(":");
                        if (document.getElementById('lm_style') != null) {
                                var lm_style = document.getElementById('lm_style').value;
                        } else {
                                var lm_style = 'normal';
                        }
                        if (document.getElementById('lm_autoload') != null) {
                                var lm_autoload = document.getElementById('lm_autoload').value;
                        } else {
                                var lm_autoload = '';
                        }
                        if (document.getElementById('lm_alreadyloaded') != null) {
                                var lm_alreadyloaded = document.getElementById('lm_alreadyloaded').value;
                        } else {
                                var lm_alreadyloaded = '';
                        }

                        $.ajax({
                                type: "GET",
                                url: me + "/backend/" + loadmore_backend + ".php?style=" + lm_style + "&mode=" + document.getElementById('lm_mode').value + "&from=" + document.getElementById('lm_from').value + "&autoload=" + lm_autoload + "&search=" + search_q + "&alreadyloaded=" + lm_alreadyloaded,
                                dataType: "xml",
                                success: function (xml) {
                                        $(xml).find('root').each(function () {
                                                var status = $(this).find('status').text();
                                                var data = $(this).find('data').text();
                                                var thumbs = $(this).find('thumbs').text();
                                                var objects = $(this).find('objects').text();
                                                var max_objects = $(this).find('max_objects').text();
                                                var overview = $(this).find('overview').text();
                                                var users = $(this).find('users').text();
                                                var alreadyloaded = $(this).find('alreadyloaded').text();
                                                if (status == 'OK') {
                                                        if (document.getElementById('lm_alreadyloaded') != null) {
                                                                document.getElementById('lm_alreadyloaded').value = document.getElementById('lm_alreadyloaded').value + alreadyloaded;
                                                        }
                                                        clearTimeout(loadmoreindicator);
                                                        if (document.getElementById('search-info') != null) {
                                                                $('#search-info').html('Search results for "' + search_q + '"');
                                                                if (users != '') {
                                                                        $('#photos-feed').append('<div class="search-users">' + users + '</div>');
                                                                }
                                                        }
                                                        $('#photos-feed').append(data);
                                                        if (document.getElementById('ex-comments-container') != null) {
                                                                $('#ex-comments-container').css("display", "block");
                                                        }
                                                        if (document.getElementById('share-this') != null && parseInt(objects) > 0) {
                                                                $('#share-this').fadeIn();
                                                        }
                                                        if (lm_mode[0] == 'exhibitionedit') {
                                                                $('#editor2').append(thumbs);
                                                                setTimeout('sortableExec();', 1000);
                                                        }
                                                        if (document.getElementById('lm_from').value == '0' && lm_autoload != '') {
                                                                if (document.getElementById('imgcontainer-' + lm_autoload) != null) {
                                                                        openPhoto(lm_autoload);
                                                                }
                                                        }
                                                        if (parseInt(objects) > 0) {
                                                                document.getElementById('lm_from').value = parseInt(document.getElementById('lm_from').value) + parseInt(objects);
                                                        }
                                                        //if(objects == max_objects || objects > max_objects) { 
                                                        if (objects < 10) {
                                                                document.getElementById('lm_active').value = '0';
                                                                document.getElementById('gallery-loadmore').style.display = 'none';
                                                                if (document.getElementById('lm_from').value == '0') {
                                                                        $('#photos-feed').html('<h2 class="header">:( <br /><br />There is nothing here, check back later</h2>');
                                                                }
                                                                if (document.getElementById('editor2-loadmore') != null) { document.getElementById('editor2-loadmore').style.display = 'none'; }
                                                        }
                                                        loadmore = '0';
                                                        $('#gallery-loadmore').css("opacity", "0");
                                                        //$('#overview').append(overview);
                                                } else {
                                                        alert(status);
                                                        loadmore = '0';
                                                        $('#gallery-loadmore').css("opacity", "0");
                                                }
                                        });
                                }
                        });
                }
        }
}

function overviewLoad() {
        if (loadmore_overview == '0' && loadmoreblock_overview == '0') {
                if (document.getElementById('lm_active_overview').value == '1') {
                        loadmore_overview = '1';
                        var lm_mode_o = document.getElementById('lm_mode').value;
                        var lm_mode = lm_mode_o.split(":");

                        $.ajax({
                                type: "GET",
                                url: me + "/backend/overview.php?mode=" + document.getElementById('lm_mode').value + "&from=" + document.getElementById('lm_from_overview').value,
                                dataType: "xml",
                                success: function (xml) {
                                        $(xml).find('root').each(function () {
                                                var status = $(this).find('status').text();
                                                var data = $(this).find('data').text();
                                                var objects = $(this).find('objects').text();
                                                var max_objects = $(this).find('max_objects').text();
                                                var overview = $(this).find('overview').text();
                                                if (status == 'OK') {
                                                        $('#overview_target').append(data);
                                                        if (parseInt(objects) > 0) {
                                                                document.getElementById('lm_from_overview').value = parseInt(document.getElementById('lm_from_overview').value) + parseInt(objects);
                                                        }
                                                        if (objects == max_objects) {

                                                        } else {
                                                                document.getElementById('lm_active_overview').value = '0';
                                                                if (document.getElementById('lm_from_overview').value == '0') {
                                                                        $('#overview_target').html('<h2 class="header">No photos found :(</h2>');
                                                                }
                                                        }
                                                        loadmore_overview = '0';
                                                } else {
                                                        alert(status);
                                                        loadmore_overview = '0';
                                                }
                                        });
                                }
                        });
                }
        }
}

function sortableExec() {
        sortable('#photos-feed', 'destroy');
        sortable('#photos-feed', { items: 'div.drag', placeholder: '<div class="drophere">Move here</div>', orientation: 'vertical' });
        sortable('#photos-feed')[0].addEventListener('sortstart', function (e) { loadmoreblock = '1'; });
        sortable('#photos-feed')[0].addEventListener('sortstop', function (e) { loadmoreblock = '0'; });
        sortable('#photos-feed')[0].addEventListener('sortupdate', function (e) { dragsync(e.detail); });

        sortable('#editor2', 'destroy');
        sortable('#editor2', { items: 'span.drag', placeholder: '<span style="margin: 0px 0px 0px -1px; position: absolute; height: 100px; border-left: 2px solid #000;display: inline-block;">&nbsp;</span>', orientation: 'horizontal' });
        sortable('#editor2')[0].addEventListener('sortstart', function (e) { loadmoreblock = '1'; });
        sortable('#editor2')[0].addEventListener('sortstop', function (e) { loadmoreblock = '0'; });
        sortable('#editor2')[0].addEventListener('sortupdate', function (e) { dragsync(e.detail); });

}

function dragsync(details) {
        var moved_id = details.item.id;
        var moved_id_s = moved_id.split("-");
        if (moved_id_s[0] == "drag2") {
                var move_from_source = '<div id="drag-' + moved_id_s[1] + '" class="drag dragimg">' + document.getElementById('drag-' + moved_id_s[1]).innerHTML + '</div>';
                var after = '';
                var last = '';
                details.origin.items.forEach(function (entry) {
                        var check = entry.id.split("-");
                        if (check[1] == moved_id_s[1] && last != '') {
                                after = 'drag-' + last;
                        }
                        last = check[1];
                });
                if (after != '') {
                        $('#drag-' + moved_id_s[1]).remove();
                        $(move_from_source).insertAfter("#" + after);
                } else {
                        $('#drag-' + moved_id_s[1]).remove();
                        $('#photos-feed').prepend(move_from_source);
                }
                sortable('#photos-feed');
        }
        if (moved_id_s[0] == "drag") {
                var move_from_source = '<span id="drag2-' + moved_id_s[1] + '" class="drag">' + document.getElementById('drag2-' + moved_id_s[1]).innerHTML + '</span>';
                var after = '';
                var last = '';
                details.origin.items.forEach(function (entry) {
                        var check = entry.id.split("-");
                        if (check[1] == moved_id_s[1] && last != '') {
                                after = 'drag2-' + last;
                        }
                        last = check[1];
                });
                if (after != '') {
                        $('#drag2-' + moved_id_s[1]).remove();
                        $(move_from_source).insertAfter("#" + after);
                } else {
                        $('#drag2-' + moved_id_s[1]).remove();
                        $('#editor2').prepend(move_from_source);
                }
                sortable('#editor2');
        }
        firstlabel();
}

function firstlabel() {
        $('.positionbuttons').css("display", "inline");
        $('.positionlabel').css("display", "none");
        var markfirst = 0;
        $('#photos-feed').children().each(function () {
                var drag_id = this.id;
                drag_id = drag_id.replace("drag-", "");
                if (parseInt(drag_id) > 0) {
                        markfirst++;
                        if (markfirst == 1) {
                                if (document.getElementById('positionbuttons-' + drag_id) != null) {
                                        $('#positionbuttons-' + drag_id).css("display", "none"); $('#positionlabel-' + drag_id).css("display", "inline");
                                }
                        }
                }
        });
}


function reorder(id) {
        if (re_order == '') {
                $('.movehere').css("display", "block");
                $('.reorderbutton').html("Abort re-order");
                $('#drag-' + id).addClass("moveselected");
                re_order = id;
                scrollto2('drag-' + re_order, 20);
        } else {
                $('#drag-' + re_order).removeClass("moveselected");
                $('.reorderbutton').html("Re-order");
                $('.movehere').css("display", "none");
                re_order = '';
        }
}

function doMove(mode, id) {
        if (re_order != '') {
                $('#drag-' + re_order).removeClass("moveselected");
                $('.reorderbutton').html("Re-order");
                $('.movehere').css("display", "none");

                var move_from_source = '<div id="drag-' + re_order + '" class="drag dragimg">' + document.getElementById('drag-' + re_order).innerHTML + '</div>';
                $('#drag-' + re_order).remove();
                if (mode == 'after') {
                        $(move_from_source).insertAfter("#drag-" + id);
                }
                if (mode == 'first') {
                        $('#photos-feed').prepend(move_from_source);
                }
                sortable('#photos-feed');

                var move_from_source = '<span id="drag2-' + re_order + '" class="drag">' + document.getElementById('drag2-' + re_order).innerHTML + '</span>';
                $('#drag2-' + re_order).remove();
                if (mode == 'after') {
                        $(move_from_source).insertAfter("#drag2-" + id);
                }
                if (mode == 'first') {
                        $('#editor2').prepend(move_from_source);
                }

                sortable('#editor2');

                scrollto2('drag-' + re_order, 20);

                re_order = '';




        }
}

function pdata(id, target) {
        if (data_loading == 0) {
                data_loading = 1;
                var pdatamode = 'non-profile';

                if (document.getElementById('is-profile') != null) {
                        pdatamode = 'profile';
                }

                document.getElementById(target).innerHTML = '<div class="loading">Loading...</div>';
                $.ajax({
                        type: "GET",
                        url: me + "/backend/pdata.php?id=" + id + "&mode=" + pdatamode,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var data = $(this).find('data').text();
                                        if (status == 'OK') {
                                                document.getElementById(target).innerHTML = data;
                                                data_loading = 0;
                                                var pic_id = id.replace("photoinfo:", "");

                                                var current_location = window.location.pathname;
                                                var ida = current_location.split("/");
                                                if (ida[2] != "popular" || ida[3] != pic_id) {
                                                        lastopenurl = window.location.pathname;
                                                        urlupdate('/photo/' + pic_id);
                                                }
                                        } else {
                                                alert(status);
                                                data_loading = 0;
                                        }
                                });
                        }
                });
        }
}

function pdata2(id, target) {
        if (data_loading == 0) {
                data_loading = 1;
                document.getElementById(target).innerHTML = '<div class="loading">Loading...</div>';
                $.ajax({
                        type: "GET",
                        url: me + "/backend/pdata.php?id=" + id,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var data = $(this).find('data').text();
                                        if (status == 'OK') {
                                                document.getElementById(target).innerHTML = data;
                                                data_loading = 0;
                                                var pic_id = id.replace("photoinfo:", "");
                                        } else {
                                                alert(status);
                                                data_loading = 0;
                                        }
                                });
                        }
                });
        }
}



function overview() {
        modal('overview', '1');
}

function overviewclose() {
        document.getElementById('overview').style.display = 'none';
}

function scroller(initial) {

        var scrolltop = $(window).scrollTop();

        // FOOBAR

        if (scrollpool > 0) {
                rightlinksmargintop = scrollpool - scrolltop;
                if (rightlinksmargintop > 0) {
                        $('#rightlinks').css("marginTop", rightlinksmargintop + "px");
                }
        }

        if (document.getElementById('pro02image') != null) {
                if (document.getElementById('pro02image').style.display == 'none') {
                        var prodiff = (parseInt($('#pro01').position().top) + parseInt($('#pro01').outerHeight(true))) + 20;
                        if (scrolltop > prodiff) {
                                $('#pro02image').css("display", "inline-block");
                        }
                }
        }

        if (document.getElementById('pro03image') != null) {
                if (document.getElementById('pro03image').style.display == 'none') {
                        var prodiff = (parseInt($('#pro02').position().top) + parseInt($('#pro02').outerHeight(true))) + 20;
                        if (scrolltop > prodiff) {
                                $('#pro03image').css("display", "inline-block");
                        }
                }
        }

        if (document.getElementById('pro05image') != null) {
                if (document.getElementById('pro05image').style.display == 'none') {
                        var prodiff = (parseInt($('#pro03').position().top) + parseInt($('#pro03').outerHeight(true))) + 20;
                        if (scrolltop > prodiff) {
                                $('#pro05image').css("display", "inline-block");
                        }
                }
        }

        if (document.getElementById('pro06image') != null) {
                if (document.getElementById('pro06image').style.display == 'none') {
                        var prodiff = (parseInt($('#pro05').position().top) + parseInt($('#pro03').outerHeight(true))) + 20;
                        if (scrolltop > prodiff) {
                                $('#pro06image').css("display", "inline-block");
                        }
                }
        }

        if (document.getElementById('chevron-down') != null) {
                if (scrolltop > 10) {
                        document.getElementById('chevron-down').style.display = 'none';
                } else {
                        document.getElementById('chevron-down').style.display = 'block';
                }
        }

        var modedetect = 0;

        if (window.getComputedStyle(document.getElementById('modedetect'), null).getPropertyValue("width") == "1px") {
                modedetect = 1;
        }

        if (window.getComputedStyle(document.getElementById('modedetect'), null).getPropertyValue("width") == "2px") {
                modedetect = 2;
        }

        if (menu == 0 && initial == '1' && automenu == '1' && modedetect == 2) {
                //toggleMenu();
        }

        if (modedetect == 2 && scrolltop > 0 && automenu == 1 && blockmenuhide == 0) {
                if (menu == 1) {
                        if (initial == '0') {
                                if (lastscrollpos < scrolltop) {
                                        toggleMenu();
                                }
                        }
                }
                if (menu == 0) {
                        if (initial == '0') {
                                if (lastscrollpos > scrolltop) {
                                        //toggleMenu();
                                }
                        }
                }
        }

        if (!foundsplash) {
                $('.splash').each(function (index) {
                        var aposition = $(this).position().top;
                        var bposition = $(this).position().top + $(this).outerHeight(true);
                        var element_theme = '1';
                        if ($(this).hasClass('splash-dark')) {
                                element_theme = '2';
                        }
                        changetheme[aposition] = element_theme;
                        changetheme[bposition] = startTheme;
                        console.log("Saved theme positions: " + aposition + "x" + bposition);
                });
                foundsplash = 1;
        }
        if (foundsplash) {
                var set_theme = 'na';
                for (var key in changetheme) {
                        if (scrolltop >= parseInt(key)) {
                                set_theme = changetheme[key];
                        }
                }
                if (set_theme == '1' || set_theme == '2') {
                        if (set_theme != currentTheme) {
                                settheme(set_theme);
                        }
                }
        }

        if (document.getElementById('left-mini') != null && document.getElementById('left-mini-scrollpast') != null) {
                var scrollpast = parseInt($('#left-mini-scrollpast').position().top) + parseInt($('#left-mini-scrollpast').outerHeight(true));
                if (scrolltop > scrollpast) {
                        $('#left-mini').removeClass("left-mini-initial");
                        $('#left-mini').removeClass("left-mini-invisible");
                        $('#left-mini').addClass("left-mini-visible");
                        leftminiactive = 1;
                } else {
                        if (leftminiactive == 1) {
                                $('#left-mini').removeClass("left-mini-visible");
                                $('#left-mini').addClass("left-mini-invisible");
                        }
                }
        }

        if (document.getElementById('lm_active') != null) {
                if (document.getElementById('lm_active').value == '1') {
                        var windowheight = $(window).height();
                        var documentheight = $(document).height();
                        var pxleft = documentheight - (scrolltop + windowheight);
                        var buffer = parseInt(windowheight * 5);
                        if (pxleft < buffer) {
                                doLoadmore();
                        }
                }
        }

        if (document.getElementById('lm_custom_enabled') != null) {
                if (document.getElementById('lm_custom_enabled').value == '1') {
                        var windowheight = $(window).height();
                        var documentheight = $(document).height();
                        var pxleft = documentheight - (scrolltop + windowheight);
                        var buffer = parseInt(windowheight * 5);
                        if (pxleft < buffer) {
                                loadmorecustom();
                        }
                }
        }


        lastscrollpos = scrolltop;
}

function enableMenu() {
        if (blockenablemenu == '0') {
                blockmenushow = '0';
        }
}

function showMenuTrigger() {
        if (typeof (window.innerWidth) == 'number') {
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
        }

        if (myWidth > myHeight) {
                showMenu();
        }
}

function hideMenuTrigger() {
        if (typeof (window.innerWidth) == 'number') {
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
        }

        if (myWidth > myHeight) {
                hideMenu();
        }
}

function showMenu() {
        if (blockmenushow == '0' && document.getElementById('menu-blocker') == null) {
                clearTimeout(menutimer);
                if (menu == 0) {
                        $('#mainmenu').switchClass("mainmenu_closed", "mainmenu_open");
                        menu = 1;
                        blockmenuhide = 1;
                }
        }
}

function hideMenu() {
        if (menu == 1) {
                clearTimeout(menutimer);
                menutimer = setTimeout('hideMenuT();', 100);
        }
}

function hideMenuT() {
        if (menu == 1) {
                $('#mainmenu').switchClass("mainmenu_open", "mainmenu_closed");
                menu = 0;
                blockmenuhide = 0;
        }
}

function toggleMenu() {
        if (menu == 0) {
                $('#mainmenu').switchClass("mainmenu_closed", "mainmenu_open");
                $('#navi-button-menu').html('Close');
                if (detect_mobile == '1') { bodystopscroll(); }
                menu = 1;
        } else {
                $('#mainmenu').switchClass("mainmenu_open", "mainmenu_closed");
                $('#navi-button-menu').html('Menu');
                if (detect_mobile == '1') { bodyscroll(); }
                menu = 0;
        }
}

var changingsplash = 0;
var currentsplash = '';

function splashchange(target, img, theme, link, copyright) {
        if (changingsplash == 0) {
                if (currentsplash != img) {
                        changingsplash = 1;
                        currentsplash = img;
                        if (theme != currentTheme) {
                                settheme(theme);
                        }
                        if (theme == '1') {
                                if ($('#' + target).hasClass("splash-dark")) {
                                        $('#' + target + ' .splash-dark').switchClass('splash-dark', 'splash-light', themeani);
                                        $('#' + target).removeClass("splash-dark");
                                        $('#' + target).addClass("splash-light");
                                }
                        } else {
                                if ($('#' + target).hasClass("splash-light")) {
                                        $('#' + target + ' .splash-light').switchClass('splash-light', 'splash-dark', themeani);
                                        $('#' + target).removeClass("splash-light");
                                        $('#' + target).addClass("splash-dark");
                                }
                        }
                        document.getElementById(target).style.backgroundImage = "url(" + img + ")";
                        $('#front-copyright').html('<a href="' + link + '">&copy; ' + copyright + '</a>');
                        setTimeout('changingsplash = 0;', themeani);
                }
        }
}

function switchtheme() {
        if (currentTheme == '1') { settheme('2'); }
        if (currentTheme == '2') { settheme('1'); }
}

function settheme(theme) {
        clearTimeout(themetimer);
        themetimer = setTimeout('navitheme(\'' + theme + '\');', 5);
}

function navitheme(theme) {
        if (switching_theme == 0) {
                switching_theme = 0;
                if (theme == '1' || theme == '2') {
                        if (theme != currentTheme) {
                                $('.themed').switchClass('theme-' + currentTheme, 'theme-' + theme, themeani);
                                $('.themedlogo-' + currentTheme).animate({ opacity: 0 }, themeani);
                                $('.themedlogo-' + theme).animate({ opacity: 1 }, themeani, function () { switching_theme = 0; });
                                currentTheme = theme;
                        }
                }
        }
}

function modalselectimg(img, target, button) {
        if (document.getElementById(target) != null) {
                if (document.getElementById('modal-selectimg-' + img) != null) {
                        if (document.getElementById('modal-selectimg-' + img).value == '1') {
                                document.getElementById('modal-selectimg-' + img).value = '0';
                        } else {
                                document.getElementById('modal-selectimg-' + img).value = '1';
                                if (document.getElementById(target).value != '') {
                                        document.getElementById(target).value = document.getElementById(target).value + ':';
                                }
                                document.getElementById(target).value = document.getElementById(target).value + img;
                        }
                }
        }
        var selectedimg = document.getElementById(target).value;
        var selectedimga = selectedimg.split(":");
        var newtarget = '';
        var counter = 1;
        selectedimga.forEach(function (entry) {
                if (document.getElementById('modal-selectimg-' + entry).value == '1') {
                        if (newtarget != '') { newtarget += ':'; }
                        newtarget += entry;
                        document.getElementById('modal-selectimg-badge-' + entry).innerHTML = counter;
                        document.getElementById('modal-selectimg-badge-' + entry).style.display = 'inline-block';
                        counter++;
                } else {
                        document.getElementById('modal-selectimg-badge-' + entry).innerHTML = '0';
                        document.getElementById('modal-selectimg-badge-' + entry).style.display = 'none';
                }
        });
        document.getElementById(target).value = newtarget;
        if (document.getElementById(button) != null) {
                if (newtarget == '') {
                        document.getElementById(button).style.opacity = '.3';
                } else {
                        document.getElementById(button).style.opacity = '1';
                }
        }
}

function selectall() {
        var newtarget = '';
        var counter = 1;
        $('.imageselected').each(function () {
                var theid1 = $(this).attr("id");
                var theid2 = theid1.replace("modal-selectimg-", "");
                if (newtarget != '') { newtarget += ':'; }
                newtarget += theid2;
                document.getElementById('modal-selectimg-badge-' + theid2).innerHTML = counter;
                document.getElementById('modal-selectimg-badge-' + theid2).style.display = 'inline-block';
                counter++;
        });
        document.getElementById('create_exhibition_photos').value = newtarget;
        document.getElementById('modal-create').style.opacity = '1';
}

function deselectall() {
        var newtarget = '';
        var counter = 0;
        $('.imageselected').each(function () {
                var theid1 = $(this).attr("id");
                var theid2 = theid1.replace("modal-selectimg-", "");
                document.getElementById('modal-selectimg-badge-' + theid2).innerHTML = '';
                document.getElementById('modal-selectimg-badge-' + theid2).style.display = 'none';
                counter++;
        });
        document.getElementById('create_exhibition_photos').value = '';
        document.getElementById('modal-create').style.opacity = '0.4';
}

function dragHide() {
        $('.draghide').css("display", "none");
}

function dragShow() {
        $('.draghide').css("display", "");
}

function preview() {
        if (document.getElementById('preview').innerHTML == 'Preview') {
                $('.exhib-editor-1-addobjects').css("display", "none");
                $('.exhib-editor-1-addobjectsspacer').css("display", "block");
                $('.exhib-editor-1').css("width", "100vw");
                $('.exhib-editor-2').css("display", "none");
                //$('.exhib-editor-3').css("display","none");
                $('#preview').html('End preview');
        } else {
                $('.exhib-editor-1-addobjects').css("display", "block");
                $('.exhib-editor-1-addobjectsspacer').css("display", "none");
                $('.exhib-editor-1').css("width", "70vw");
                $('.exhib-editor-2').css("display", "block");
                $('#preview').html('Preview');
        }
}

function align(pic_id, orientation, align) {
        exhibedit(document.getElementById('exhibition_id').value, 'align:' + pic_id + ':' + orientation + ':' + align + ':');
}

function scrollto(id, offset) {
        $('html, body').animate({
                scrollTop: $("#" + id).offset().top - offset
        }, 500);
}

function scrollto2(id, offset) {
        $('html, body').scrollTop($("#" + id).offset().top - offset);
}

function createUpload(id) {
        $('#modal-uploaded-parent').prepend('<span class="modal-uploader-new animated zoomIn" id="uploader-' + id + '"><span class="modal-uploader-new-progress" id="uploader-progress-' + id + '">0%</span></span> ');
}

function circlePosition(what, val) {
        var $circle = $('#svg' + what + ' #bar' + what);

        if (isNaN(val)) {
                val = 100;
        }
        else {
                var r = $circle.attr('r');
                var c = Math.PI * (r * 2);

                if (val < 0) { val = 0; }
                if (val > 100) { val = 100; }

                var pct = ((100 - val) / 100) * c;

                $circle.css({ strokeDashoffset: pct });

                $('#cont' + what).attr('data-pct', val);
        }
}

function getMessages(from, openfirst) {

        if (typeof (window.innerWidth) == 'number') {
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
        }

        $('#messages_loadmore').css("display", "none");
        $('#messages_list').html('');
        $('#messages_editor').css("display", "none");

        var found = 0;
        var first = '';
        $.ajax({
                type: "GET",
                url: "/backend/messages.php?from=" + from,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status != 'OK') {
                                        alert(status);
                                } else {
                                        document.getElementById('loader').style.display = 'none';
                                        if (from == 0) {
                                                $('#messages_list').html('<div style="margin: 0px 0px 40px 0px;"><span class="button jade medium" onclick="createMsg();">New</span></div>');
                                        }
                                }
                        });
                        $(xml).find('mail').each(function () {
                                var id = $(this).find('id').text();
                                var unread = $(this).find('unread').text();
                                var subject = $(this).find('subject').text();
                                var from = $(this).find('from').text();
                                var profilepic = $(this).find('profilepic').text();
                                if (first == '') { first = id; }
                                found++;
                                if (parseInt(unread) > 0) { var isunread = '_unread'; } else { var isunread = ''; }
                                var l_data = '<div class="messages-mail';
                                if (parseInt(unread) > 0) { l_data += ' messages-mail-unread'; }
                                l_data += '" style="cursor: pointer;" id="list_msg_' + id + '" onclick="loadMessage(\'' + id + '\');">';
                                //if(parseInt(unread) > 0) { l_data += '<span id="unread_' + id + '" style="position: relative; top: 1em;" class="tag tag-danger tag-pill pull-xs-right">' + unread + '</span>'; }
                                l_data += '<img src="https://seuppcdn01.1x.com/images/profile/' + profilepic + '-square.jpg" style="width: 2.5em; height: 2.5em; float: left;"><div style="padding: 0px 0px 0px 3.5em;"><div style="white-space: nowrap; overflow: hidden;" class="list_subject' + isunread + '" id="list_subject_' + id + '">' + subject + '</div><div class="list_from' + isunread + '" id="list_from_' + id + '">' + from + '</div></div></div>';
                                $('#messages_list').append(l_data);
                        });

                        document.getElementById('msg_count').value = parseInt(document.getElementById('msg_count').value) + found;

                        if (found == 50) {
                        }
                        if (found == 0) {
                                $('#messages_list').append('<div class="messages-mail"><div style="font-size: 0.9em; color: #aaa; font-weight: 300; text-align: center;">Your inbox is empty</div></div>');
                        }
                        if (first != '' && openfirst == 1 && myWidth > myHeight) {
                                loadMessage(first);
                        }

                }
        });
}

function loadMessage(id) {
        $('#messages_reader').html('');
        $('#messages_reader').css("display", "block");
        $('#messages_reader_h').html('');
        $('#messages_reader_h').css("display", "block");
        $('#messages_editor').css("display", "block");
        document.getElementById('msg_text').value = '';

        if (typeof (window.innerWidth) == 'number') {
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
        }

        if (parseInt(myWidth) < 1150) {
                $('#messages_list_master').css("display", "none");
        }

        if (openmsg != '') {
                $('#list_msg_' + openmsg).removeClass("active");
        }

        $('#list_msg_' + id).addClass("active");
        openmsg = id;

        $.ajax({
                type: "GET",
                url: "/backend/message.php?id=" + id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var subject = $(this).find('subject').text();
                                var between = $(this).find('between').text();
                                var mass = $(this).find('mass').text();
                                if (status != 'OK') {
                                        alert(status);
                                } else {
                                        $('#messages_editor').css("display", "block");
                                        $('#messages_reader_h').html('<span class="msg_icons"><span class="msg_icon_group" onclick="deleteMsg(\'' + id + '\');"><span class="msg_icon"><i class="far fa-trash-alt"></i></span> <span class="msg_icon_label">Delete</span></span></span><div class="messages_reader_header"><div id="messages_reader_header_subject" class="messages_reader_header_subject">' + subject + '</div><div class="messages_reader_header_between">' + between + '</div></div>');
                                        if (mass == '1') { disableMsgEditor(); } else { enableMsgEditor(); }
                                }
                        });
                        $(xml).find('msg').each(function () {
                                var user_id = $(this).find('user_id').text();
                                var name = $(this).find('name').text();
                                var username = $(this).find('username').text();
                                var profilepic = $(this).find('profilepic').text();
                                var me = $(this).find('me').text();
                                var text = $(this).find('text').text();
                                var msgdate = $(this).find('msgdate').text();
                                if (me == '1') { var bubble = 'bubble'; var align = 'right'; } else { var bubble = 'bubble2'; var align = 'left'; }
                                var m_data = '<div class="bubble_outer" align="' + align + '"><table border="0" cellpadding="0" cellspacing="0"><tr>';
                                if (me != '1') {
                                        m_data += '<td style="width: 3.7em; padding: 0px 0px 1em 0px;"><img src="https://seuppcdn01.1x.com/images/profile/' + profilepic + '-square.jpg" style="width: 2em; height: 2em;"></td>';
                                }
                                m_data += '<td><div class="' + bubble + '"><div style="padding: 1em; font-size: 0.9em; font-weight: 500;">' + text + '</div></div><div style="font-size: 0.7em; color: #999; padding: 0.7em 0px 0px 0px; font-weight: 300;" align="' + align + '">' + name + " " + msgdate + '</div></td>';
                                if (me == '1') {
                                        m_data += '<td style="width: 3.7em; padding: 0px 0px 1em 0px;" align="right"><img src="https://seuppcdn01.1x.com/images/profile/' + profilepic + '-square.jpg" style="width: 2em; height: 2em;"></td>';
                                }
                                m_data += '</tr></table></div>';
                                $('#messages_reader').append(m_data);
                        });
                        $('#modal-inner-block2').scrollTop($('#modal-inner-block2')[0].scrollHeight);
                        $('#list_subject_' + id).removeClass("list_subject_unread");
                        $('#list_subject_' + id).addClass("list_subject");
                        $('#list_from_' + id).removeClass("list_from_unread");
                        $('#list_from_' + id).addClass("list_from");
                        if (document.getElementById('unread_' + id) != null) {
                                $('#unread_' + id).css("display", "none");
                        }
                        autosize($('#msg_text'));
                }
        });
}

function compressUpdate(blockshow) {
        var amount = parseInt(document.getElementById('morehidden-' + blockshow).value);
        amount = amount + 1;
        document.getElementById('morehidden-' + blockshow).value = amount;
        document.getElementById('more-' + blockshow).innerHTML = ' and ' + amount + ' more ';
}

function setHeight() {
        var reduce = 100;

        if (typeof (window.innerWidth) == 'number') {
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
        }

        var setheight = parseInt(myHeight) - reduce;

        if (openmsg != '') {
                if (parseInt(myWidth) < 1150) {
                        $('#messages_list_master').css("display", "none");
                } else {
                        $('#messages_list_master').css("display", "block");
                }
        }

        if (parseInt(myWidth) < 1150) {
                var reader_height = myHeight - 55 - 100 - 65;
                document.getElementById('messages_reader').style.height = reader_height + 'px';
        } else {
                document.getElementById('messages_reader').style.height = '100%';
        }

}

function enableMsgEditor() {
        $('#btn_msg_send').removeClass("disabled");
        $("#btn_msg_send").removeAttr("disabled");
        $("#msg_text").removeAttr("disabled");

        if (typeof (window.innerWidth) == 'number') {
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
        }

        if (parseInt(myWidth) > 1149) {
                $('#msg_text').focus();
        }

}

function critiqueWrite() {
        var cdesc = document.getElementById('critique_desc').value;
        var remaining = 500 - cdesc.length;
        if (remaining > 0) {
                $('#critique_remaining').html("Write " + remaining + " more characters");
                $('#postforcritique').css("opacity", "0.3");
        } else {
                $('#critique_remaining').html("");
                $('#postforcritique').css("opacity", "1");
        }
}


function sendMsg() {
        if ($("#btn_msg_send").attr("disabled") == "disabled") {
                alert('This message cannot be replied to');
        } else {
                if (openmsg != '') {
                        var msg_text = document.getElementById('msg_text').value;
                        if (msg_text.length > 1) {

                                document.getElementById('msg_text').value = '';
                                document.getElementById('loader').style.display = 'block';

                                $.ajax({
                                        type: "POST",
                                        url: "/backend/sendmsg.php",
                                        data: { id: openmsg, text: msg_text },
                                        dataType: "xml",
                                        success: function (xml) {
                                                $(xml).find('root').each(function () {
                                                        var status = $(this).find('status').text();
                                                        if (status == 'OK') {
                                                                document.getElementById('msg_text').value = '';
                                                                $('#msg_text').css("height", "unset");
                                                                loadMessage(openmsg);
                                                                document.getElementById('loader').style.display = 'none';
                                                        } else {
                                                                alert(status);
                                                        }
                                                });
                                        }
                                });

                        } else {
                                alert('Message is too short');
                        }
                } else {
                        alert('No message open, cannot send...');
                }
        }
}

function createMsg(to, toname) {
        modal('sendmsg', '', '2');
}

function msgFocusSubject() {
        document.getElementById('message-subject').focus();
}

function msgFocusRec() {
        document.getElementById('token-input-recipient-name').focus();
}

var messages_search_timer;
var message_search_selected = 0;
var messages_search_lastsearch = '';

function messagesSearch(q) {
        if (q != messages_search_lastsearch) {
                clearTimeout(messages_search_timer);
                messages_search_timer = setTimeout('messagesSearchDo();', 200);
        }
}

function messagesSearchDo() {

        var q = document.getElementById('message_tofind').value;
        message_search_selected = 0;
        var put = '';
        var foundusers = 0;

        if (q && messages_search_lastsearch != q) {
                $.ajax({
                        type: "GET",
                        url: "/backend/searchuser.php?q=" + q,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('searchuser').each(function () {
                                        var mail_name = $(this).find('name').text();
                                        var mail_userid = $(this).find('userid').text();
                                        var mail_profilepic = $(this).find('profilepic').text();
                                        var mail_title = $(this).find('title').text();
                                        if (document.getElementById('added-' + mail_userid) == null && document.getElementById('isgroupmember-' + mail_userid) == null) {
                                                foundusers++;
                                                if (foundusers == 1) { message_search_selected = 1; var selected = '_active'; } else { var selected = ''; }
                                                put += '<div onmousedown="messagesAddTo(\'' + foundusers + '\');" id="search_hit_' + foundusers + '" class="messages_search_item' + selected + '"><input type="hidden" id="search_hit_userid_' + foundusers + '" value="' + mail_userid + '"><input type="hidden" id="search_hit_name_' + foundusers + '" value="' + mail_name + '"><table border="0" cellpadding="0" cellspacing="0"><tr><td width="50"><img src="https://1x.com/images/profile/' + mail_profilepic + '-square.jpg" style="height: 40px; width: 40px;"></td><td><div>' + mail_name + '</div></td></tr></table></div>';
                                        }
                                });
                                document.getElementById('user_search').innerHTML = put;
                                messages_search_lastsearch = q;
                        }
                });
                if (0) {
                        document.getElementById('user_search').innerHTML = '<div style="padding: 10px; color: #ccc; font-size: 13px;">No results found for "' + q + '"</div>';
                }
        }
}

function messagesAddTo(count) {
        if (document.getElementById('search_hit_userid_' + count) != null) {
                var add_userid = document.getElementById('search_hit_userid_' + count).value;
                if (document.getElementById('added-' + add_userid) == null) {
                        if (document.getElementById('message_to_span').innerHTML == 'No recipients selected') {
                                document.getElementById('message_to_span').innerHTML = document.getElementById('search_hit_name_' + count).value + ' <span style="cursor: pointer;" onclick="messagesDeleteTo(\'' + add_userid + '\');">(x)</span>';
                        } else {
                                document.getElementById('message_to_span').innerHTML += ', ' + document.getElementById('search_hit_name_' + count).value + ' <span style="cursor: pointer;" onclick="messagesDeleteTo(\'' + add_userid + '\');">(x)</span>';
                        }
                        document.getElementById('message_to_hiddens').innerHTML += '<input type="hidden" id="added-' + add_userid + '" value="' + document.getElementById('search_hit_name_' + count).value + '">';
                        if (document.getElementById('message_to').value != '') {
                                document.getElementById('message_to').value = document.getElementById('message_to').value + ',' + add_userid;
                        } else {
                                document.getElementById('message_to').value = add_userid;
                        }
                        document.getElementById('message_tofind').value = '';
                        messages_search_lastsearch = '';
                        document.getElementById('user_search').innerHTML = '<div style="padding: 10px; color: #ccc; font-size: 13px;">Type to add more recipients</div>';
                        setTimeout('document.getElementById(\'message_tofind\').focus();', 100);
                }
        }
}

function messagesAddToUser(add_userid, add_name) {
        if (document.getElementById('added-' + add_userid) == null) {
                if (document.getElementById('message_to_span').innerHTML == 'No recipients selected') {
                        document.getElementById('message_to_span').innerHTML = add_name + ' <span style="cursor: pointer;" onclick="messagesDeleteTo(\'' + add_userid + '\');">(x)</span>';
                } else {
                        document.getElementById('message_to_span').innerHTML += ', ' + add_name + ' <span style="cursor: pointer;" onclick="messagesDeleteTo(\'' + add_userid + '\');">(x)</span>';
                }
                document.getElementById('message_to_hiddens').innerHTML += '<input type="hidden" id="added-' + add_userid + '" value="' + add_name + '">';
                if (document.getElementById('message_to').value != '') {
                        document.getElementById('message_to').value = document.getElementById('message_to').value + ',' + add_userid;
                } else {
                        document.getElementById('message_to').value = add_userid;
                }
                document.getElementById('message_tofind').value = '';
                messages_search_lastsearch = '';
                document.getElementById('user_search').innerHTML = '<div style="padding: 10px; color: #ccc; font-size: 13px;">Type to add more recipients</div>';
                setTimeout('document.getElementById(\'message-subject\').focus();', 100);
        }
}

function messagesDeleteTo(theuserid) {
        var current_to = document.getElementById('message_to').value;
        var current_to_array = new Array();
        current_to_array = current_to.split(",");
        var arrayloop = 0;
        var message_to_new = '';
        var message_to_span_new = '';
        var message_to_hiddens_new = '';
        while (arrayloop != current_to_array.length) {
                if (current_to_array[arrayloop] != theuserid && parseInt(current_to_array[arrayloop]) > 0) {
                        if (message_to_new != '') {
                                message_to_new += ',' + current_to_array[arrayloop];

                        } else {
                                message_to_new = current_to_array[arrayloop];
                        }
                        message_to_hiddens_new += '<input type="hidden" id="added-' + current_to_array[arrayloop] + '" value="' + document.getElementById('added-' + current_to_array[arrayloop]).value + '">';
                        if (message_to_span_new == '') {
                                message_to_span_new = document.getElementById('added-' + current_to_array[arrayloop]).value + ' <span style="cursor: pointer;" onclick="messagesDeleteTo(\'' + current_to_array[arrayloop] + '\');">(x)</span>';
                        } else {
                                message_to_span_new += ', ' + document.getElementById('added-' + current_to_array[arrayloop]).value + ' <span style="cursor: pointer;" onclick="messagesDeleteTo(\'' + current_to_array[arrayloop] + '\');">(x)</span>';
                        }
                }
                arrayloop++;
        }
        if (message_to_span_new == '') { message_to_span_new = 'No recipients selected'; }
        document.getElementById('message_to').value = message_to_new;
        document.getElementById('message_to_span').innerHTML = message_to_span_new;
        document.getElementById('message_to_hiddens').innerHTML = message_to_hiddens_new;
}

function messagesSelect() {
        if (message_search_selected > 0) {
                messagesAddTo(message_search_selected);
        }
        return false;
}

function messagesUp() {
        if (message_search_selected > 0) {
                var nextmessage = message_search_selected - 1;
                if (document.getElementById('search_hit_' + nextmessage) != null) {
                        document.getElementById('search_hit_' + message_search_selected).setAttribute("class", "messages_search_item");
                        message_search_selected = nextmessage;
                        document.getElementById('search_hit_' + message_search_selected).setAttribute("class", "messages_search_item_active");

                }
        }
        return false;
}

function messagesDown() {
        if (message_search_selected > 0) {
                var nextmessage = message_search_selected + 1;
                if (document.getElementById('search_hit_' + nextmessage) != null) {
                        document.getElementById('search_hit_' + message_search_selected).setAttribute("class", "messages_search_item");
                        message_search_selected = nextmessage;
                        document.getElementById('search_hit_' + message_search_selected).setAttribute("class", "messages_search_item_active");

                }
        }
        return false;
}

function sendmail(to, subject, text) {
        if (to && subject && text) {
                $.ajax({
                        type: "POST",
                        url: me + "/backend/sendmail.php",
                        data: { to: to, subject: subject, text: text },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                closeModal2();
                                                modal('messenger', '1');
                                                mixpanel.track('Created a conversation');
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        } else {
                alert('You must select at least one recipient and write a subject and a text');
        }
}

function writeBlogComment(id, reply_to) {
        $('#blogcomments_' + id).css("opacity", "0.2");
        if (!reply_to) {
                var comment = document.getElementById('writeblogcomment_' + id).value;
        } else {
                var comment = document.getElementById('writeblogcommentreply_' + reply_to).value;
        }
        $.ajax({
                type: "POST",
                url: "/backend/writeblogcomment.php",
                data: { id: id, text: comment, reply_to: reply_to },
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var c_id = $(this).find('c_id').text();
                                if (status == 'OK') {
                                        if (!reply_to) {
                                                $('#blogcomments_' + id).css("opacity", "1");
                                                document.getElementById('writeblogcomment_' + id).value = '';
                                                document.getElementById('writebutton_' + id).style.opacity = '0.3';
                                                var data = '<div class="magazine_comments_comment" id="blogcomment_' + c_id + '"><table width="100%" border="0" cellpadding="0" cellspacing="0"><tbody><tr><td width="55" valign="top"><img src="https://1x.com/images/profile/' + auth_img + '-square.jpg" style="width: 40px; height: 40px;"> </td><td><div class="magazine_comments_comment_name"><a href="/' + auth_username + '">' + auth_name + '</a></div><div class="magazine_comments_comment_text">' + comment + '</div><div class="magazine_comments_links"><a href="#" class="magazine_comments_link" style="color: #888;">Just now</a><a href="javascript:void(0);" class="magazine_comments_link" onclick="blogCommentReply(\'' + id + '\',\'' + c_id + '\');">Reply</a><a href="javascript:void(0);" class="magazine_comments_link" onclick="deleteBlogComment(\'' + c_id + '\');">Delete</a></div></td></tr></tbody></table></div>';
                                                $('#magazine_newcomments_' + id).append(data);
                                        } else {
                                                $('#blogcomments_' + id).css("opacity", "1");
                                                document.getElementById('writeblogcommentreply_' + reply_to).value = '';
                                                document.getElementById('writebuttonreply_' + reply_to).style.opacity = '0.3';
                                                var data = '<div class="magazine_comments_replies_reply"><table width="100%" border="0" cellpadding="0" cellspacing="0"><tbody><tr><td width="43" valign="top"><img src="/images/profile/' + auth_img + '-square.jpg" style="width: 30px; height: 30px;"></td><td><div class="magazine_comments_replies_name"><a href="/' + auth_username + '">' + auth_name + '</a></div><div class="magazine_comments_replies_text">' + comment + '</div></td></tr></tbody></table></div>';
                                                $('#repliestarget_' + reply_to).prepend(data);
                                                $('#repliestarget_' + reply_to).css("display", "block");
                                                $('#creply-' + reply_to).css("display", "none");
                                        }
                                } else {
                                        $('#blogcomments_' + id).css("opacity", "1");
                                        alert(status);
                                }
                        });
                }
        });
}


function blogCommentReply(blog_id, comment_id) {
        var editor = '<div class="magazine_comments_textareacontainerreply"><table border="0" cellpadding="0" cellspacing="0"><tr><td width="50" valign="top"><img src="https://1x.com/images/profile/' + auth_img + '-square.jpg" style="height: 30px; width: 30px;"></td><td width="550"><textarea onkeyup="if(this.value != \'\') { document.getElementById(\'writebuttonreply_' + comment_id + '\').style.opacity = \'1\'; } else { document.getElementById(\'writebuttonreply_' + comment_id + '\').style.opacity = \'0.3\'; } " id="writeblogcommentreply_' + comment_id + '" class="magazine_comments_textarea_reply" placeholder="Write your reply here"></textarea></td><td><div class="magazine_comments_writebuttoncontainer"><span class="button medium jade" id="writebuttonreply_' + comment_id + '" style="opacity: .3;" onclick="writeBlogComment(\'' + blog_id + '\',\'' + comment_id + '\');">Reply</span></div></td></tr></table></div>';
        $('#creply-' + comment_id).css("display", "block");
        $('#creply-' + comment_id).html(editor);
        $('#writeblogcommentreply_' + comment_id).focus();
        autosize($('#writeblogcommentreply_' + comment_id));
}



function startSubscriptionSCA() {
        var period = '';
        if (document.getElementById('sub_3').checked == 1) { period = '3'; }
        if (document.getElementById('sub_6').checked == 1) { period = '6'; }
        if (document.getElementById('sub_12').checked == 1) { period = '12'; }
        if (period == '3' || period == '6' || period == '12') {

                $.ajax({
                        type: "GET",
                        url: "/backend/subscribesca.php?period=" + period,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var session_id = $(this).find('session_id').text();
                                        if (status == 'OK' && session_id != '') {
                                                var stripe = Stripe('pk_live_VGSuidqac3TYCEVL1C7qRj7A');

                                                stripe.redirectToCheckout({
                                                        sessionId: session_id
                                                }).then(function (result) {
                                                });
                                        } else { alert(status); }
                                });
                        }
                });

        }
}

function resetPayment(period) {

        $.ajax({
                type: "GET",
                url: "/backend/resetpayment.php",
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        startSubscriptionSCA2(period);
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function startSubscriptionSCA2(period) {
        if (period == '1' || period == '3' || period == '12' || period == '12t' || period == '1tr' || period == '3tr' || period == '12tr' || period == '12bw') {

                nloader('Connecting to payment provider. Please wait... If you waited more than 1 minute, contact support@1x.com');

                $.ajax({
                        type: "GET",
                        url: "/backend/subscribesca.php?period=" + period,
                        dataType: "xml",
                        error: function () {
                                setTimeout('resetPayment(\'' + period + '\');', 1000);
                        },
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var session_id = $(this).find('session_id').text();
                                        if (status == 'OK' && session_id != '') {
                                                //mixpanel.track('Initiating subscription', {"Plan": period });

                                                var stripe = Stripe('pk_live_VGSuidqac3TYCEVL1C7qRj7A');

                                                stripe.redirectToCheckout({
                                                        sessionId: session_id
                                                }).then(function (result) {
                                                });
                                        } else { alert(status); }
                                });
                        }
                });

        }
}


function makeSCAPayment() {
        var code = document.getElementById('accesscode').value;
        document.getElementById('paymentform').style.opacity = '0.2';
        var period = '';
        if (document.getElementById('period_3').checked == 1) { period = '3'; }
        if (document.getElementById('period_6').checked == 1) { period = '6'; }
        if (document.getElementById('period_12').checked == 1) { period = '12'; }
        if (period == '3' || period == '6' || period == '12') {

                $.ajax({
                        type: "GET",
                        url: "/backend/subscribesca.php?period=" + period + "&code=" + code,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var session_id = $(this).find('session_id').text();
                                        if (status == 'OK' && session_id != '') {
                                                var stripe = Stripe('pk_live_VGSuidqac3TYCEVL1C7qRj7A');

                                                stripe.redirectToCheckout({
                                                        sessionId: session_id
                                                }).then(function (result) {
                                                });
                                        } else { alert(status); }
                                });
                        }
                });

        }
}


function cancelSubscription() {
        $.ajax({
                type: "GET",
                url: "/backend/cancelsubscription.php",
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        mixpanel.track('Cancelled subscription');
                                        location.href = '/subscribe';
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function subPrice() {

        var subscribe2_planselected = '12';

        if (document.getElementById('sub_12').checked == 1) {
                subscribe2_planselected = '12';
        }
        if (document.getElementById('sub_6').checked == 1) {
                subscribe2_planselected = '6';
        }
        if (document.getElementById('sub_3').checked == 1) {
                subscribe2_planselected = '3';
        }

        if (document.getElementById('plan_half') == null) {
                if (subscribe2_planselected == '12') { var price = '71.88'; var period = '12 months'; }
                if (subscribe2_planselected == '6') { var price = '47.94'; var period = '6 months'; }
                if (document.getElementById('3moffer') == null) {
                        if (subscribe2_planselected == '3') { var price = '29.97'; var period = '3 months'; }
                } else {
                        if (subscribe2_planselected == '3') { var price = '14.98'; var period = '3 months'; }
                }
        } else {
                if (subscribe2_planselected == '12') { var price = '35.94 first year, and then 71.88'; var period = '12 months'; }
                if (subscribe2_planselected == '6') { var price = '23.97 first half year, and then 47.94'; var period = '6 months'; }
                if (subscribe2_planselected == '3') { var price = '14.98 first 3 months, and then 29.97'; var period = '3 months'; }
        }

        document.getElementById('subscribe2_price').innerHTML = price;
        document.getElementById('subscribe2_period').innerHTML = period;
}

function deleteExhibition() {
        $.ajax({
                type: "GET",
                url: "/backend/deleteexhibition.php?id=" + document.getElementById('exhibition_id').value,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        location.href = '/' + auth_username;
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function saveexhibition() {
        var object_str = '';
        $('#photos-feed').children().each(function () {
                var drag_id = this.id;
                drag_id = drag_id.replace("drag-", "");
                if (parseInt(drag_id) > 0) {
                        object_str += drag_id + ':';
                }
        });

        if (object_str != '') {
                $.ajax({
                        type: "GET",
                        url: "/backend/saveorder.php?id=" + document.getElementById('exhibition_id').value + "&order=" + object_str + "&title=" + document.getElementById('exhib_title').value,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                $('#savestatus').html("Changes saved!");
                                                setTimeout('$(\'#savestatus\').html(\'\');', 2000);
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}

function deleteMsg(id) {
        document.getElementById('loader').style.display = 'block';
        $.ajax({
                type: "GET",
                url: "/backend/deletemsg.php?id=" + id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        controlcenter('messages', 1);
                                }
                        });
                }
        });
}


function editMsg(id, topic_id, main) {
        modal('editmsg:' + id + ':' + topic_id + ':' + main + ':', '1');
}

function saveForumEdit() {

        var id = document.getElementById('edit_msg_id').value;
        var topic_id = document.getElementById('edit_topic_id').value;

        if (parseInt(id) > 0 && parseInt(topic_id) > 0) {
                var changename = '';
                if (document.getElementById('editforum-name-section').style.display == 'block') {
                        if (document.getElementById('editforum-name').value != '') {
                                changename = document.getElementById('editforum-name').value;
                        }
                }
                $.ajax({
                        type: "POST",
                        url: "/backend/saveforumedit.php",
                        data: { id: id, topic_id: topic_id, text: document.getElementById('editforum-text').value, subject: changename },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var rawtext = $(this).find('rawtext').text();
                                        var text = $(this).find('text').text();
                                        var edited = $(this).find('edited').text();
                                        var topictitle = $(this).find('topictitle').text();
                                        if (status == 'OK') {
                                                closeModal();
                                                document.getElementById('forum_text_' + id).innerHTML = text;
                                                document.getElementById('rawtext_' + id).innerHTML = rawtext;
                                                document.getElementById('lastedited_' + id).innerHTML = edited;
                                                if (topictitle != '') {
                                                        document.getElementById('forum_topic_header_title').innerHTML = topictitle;
                                                        document.getElementById('topicname').value = topictitle;
                                                }
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        }
}

function quoteMsg(id) {
        var text = striphtml(document.getElementById('rawtext_' + id).innerHTML);

        document.getElementById('forum_message').value = document.getElementById('forum_message').value + '[QUOTE ' + id + ']' + text + '[/QUOTE]\n\n';

        var element = document.getElementById('forum_message');

        element.focus();
        element.setSelectionRange(element.value.length, element.value.length);
        element.scrollTop = element.scrollHeight;

        $('#btn_forum_send').css("opacity", "1");

        autosize.update($('#forum_message'));


}


function striphtml(html) {
        var tmp = document.createElement("DIV");
        tmp.innerHTML = html;
        return tmp.textContent || tmp.innerText || "";
}


function sendForumMsg(topic_id, forum_id) {
        if (topic_id && forum_id) {
                if (document.getElementById('forum_message').value != '') {
                        $('#btn_forum_send').addClass('disabled');
                        document.getElementById('forum_message').readOnly = true;
                        document.getElementById('forum_reply').style.opacity = '.2';
                        document.getElementById('forum_thread_loader_write').style.display = 'block';


                        $.ajax({
                                type: "POST",
                                url: "/backend/forumpost.php",
                                data: { topic_id: topic_id, forum_id: forum_id, text: document.getElementById('forum_message').value },
                                dataType: "xml",
                                success: function (xml) {
                                        $(xml).find('root').each(function () {
                                                var status = $(this).find('status').text();
                                                if (status == 'OK') {
                                                        document.getElementById('forum_message').value = '';
                                                        getForumPosts(topic_id, document.getElementById('forum_thread_latest').value);
                                                        document.getElementById('forum_message').readOnly = false;
                                                        document.getElementById('forum_reply').style.opacity = '1';
                                                        document.getElementById('forum_thread_loader_write').style.display = 'none';
                                                } else {
                                                        alert(status);
                                                }
                                        });
                                }
                        });


                }
        }
}

function writeCurationResponse(id) {
        var comment = document.getElementById('photo-detail-writecomment-' + id).value;
        if (comment != '') {
                $.ajax({
                        type: "POST",
                        url: "/backend/writecurationresponse.php",
                        data: { id: id, comment: document.getElementById('photo-detail-writecomment-' + id).value },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                document.getElementById('photo-detail-writecomment-' + id).value = '';
                                                document.getElementById('photo-detail-writebutton-' + id).style.opacity = '0.4';
                                                var responsehtml = '<div class="critique-dashboard-response"><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr><td width="60" valign="top"><img src="https://seuppcdn01.1x.com/images/profile/' + auth_img + '-square.jpg" style="width: 40px;"></td><td valign="top"><div class="critique-dashboard-response-comment"><div class="critique-dashboard-response-name">' + auth_name + '</div>' + comment + '</div></td></tr></table></div>';
                                                $('#responses-' + id).append(responsehtml);
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        } else {
                alert("You must write a comment");
        }
}

function writeCommentCuration(id) {
        var comment = document.getElementById('photo-detail-writecomment-' + id).value;
        if (comment != '') {
                $.ajax({
                        type: "POST",
                        url: "/backend/writecomment.php",
                        data: { id: id, comment: document.getElementById('photo-detail-writecomment-' + id).value },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                document.getElementById('photo-detail-writecomment-' + id).value = '';
                                                document.getElementById('photo-detail-writebutton-' + id).style.opacity = '0.4';
                                                $('#curationcomment-' + id).html('<div class="curation-writecomment" style="background: #fff;"><div class="curation-writecomment-header">You commented</div><div class="curation-writecomment-comment">' + comment + '</div></div>');
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        } else {
                alert("You must write a comment");
        }
}


function writeComment(id) {
        var comment = document.getElementById('photo-detail-writecomment-' + id).value;
        if (comment != '') {
                $.ajax({
                        type: "POST",
                        url: "/backend/writecomment.php",
                        data: { id: id, comment: document.getElementById('photo-detail-writecomment-' + id).value },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                document.getElementById('photo-detail-writecomment-' + id).value = '';
                                                document.getElementById('photo-detail-writebutton-' + id).style.opacity = '0.4';
                                                var commenthtml = '<div class="photo-detail-comment"><div class="photo-detail-comment-name">' + auth_name;
                                                if (auth_membership == '1') {
                                                        commenthtml += ' <span class="pro-label-medium">' + auth_title + '</span>';
                                                }
                                                commenthtml += '</div><div class="photo-detail-comment-text">' + comment + '</div></div>';
                                                $('#comments-' + id).prepend(commenthtml);
                                                $('#nocomments-' + id).css("display", "none");
                                        } else {
                                                alert(status);
                                        }
                                });
                        }
                });
        } else {
                arrowbox('You must write a comment first', 'photo-detail-writecomment-div-' + id, 70, 0);
        }
}

function arrowbox(msg, element, offsettop, offsetleft) {
        var boxtop = ($("#" + element).offset().top + offsettop) + 'px';
        var boxleft = ($("#" + element).offset().left + offsetleft) + 'px';
        $('#arrowbox-target').html('<div style="position: absolute; top: ' + boxtop + '; left: ' + boxleft + ';"><div class="arrow_box animated headShake">' + msg + '</div></div>');
}

function arrowboxhide() {
        $('#arrowbox-target').html('');
}

function notCount() {
        $.ajax({
                type: "GET",
                url: "/backend/notcount.php",
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var nc_all = $(this).find('nc_all').text();
                                var nc_not = $(this).find('nc_not').text();
                                var nc_msg = $(this).find('nc_msg').text();
                                var dlogin = $(this).find('login').text();
                                if (parseInt(dlogin) > 0) {
                                        if (document.getElementById('rightbubble-notification') != null) {
                                                if (nc_all > 0) {
                                                        document.title = '[' + nc_all + '] ' + basetitle;
                                                } else {
                                                        document.title = basetitle;
                                                }
                                                if (nc_not > 0) {
                                                        $('#rightbubble-notification').addClass("rightbubble-on");
                                                        $('#rightbubble-notification2').addClass("rightbubble-on");
                                                } else {
                                                        $('#rightbubble-notification').removeClass("rightbubble-on");
                                                        $('#rightbubble-notification2').removeClass("rightbubble-on");
                                                }
                                                if (nc_msg > 0) {
                                                        $('#rightbubble-message').addClass("rightbubble-on");
                                                        $('#rightbubble-message2').addClass("rightbubble-on");
                                                } else {
                                                        $('#rightbubble-message').removeClass("rightbubble-on");
                                                        $('#rightbubble-message2').removeClass("rightbubble-on");
                                                }
                                        } else {
                                                if (nc_all > 0) {
                                                        $('#notification_red').css("display", "inline");
                                                        $('#navi-button-notification').css("display", "inline-block");
                                                        document.title = '[' + nc_all + '] ' + basetitle;
                                                } else {
                                                        $('#notification_red').css("display", "none");
                                                        $('#navi-button-notification').css("display", "none");
                                                        document.title = basetitle;
                                                }
                                        }
                                        clearTimeout(nottimer);
                                        nottimer = setTimeout('notCount();', 60000);
                                }
                        });
                }
        });
}


function checkSettings() {
        document.getElementById('settings_btn').style.opacity = '0.5';
        document.getElementById('settings_saved').style.display = 'none';

        var s_error = '';
        if (document.getElementById('s_name').value == '') {
                s_error = 'You must enter a name';
        }

        if (document.getElementById('s_email').value == '') {
                s_error = 'You must enter an e-mail address';
        }

        if (document.getElementById('s_pw2').value != '') {
                if (document.getElementById('s_pw3').value == '') {
                        s_error = 'You must repeat your new password';
                }
                if (document.getElementById('s_pw1').value == '') {
                        s_error = 'You must enter your current password';
                }
                if (document.getElementById('s_pw3').value != document.getElementById('s_pw2').value) {
                        s_error = 'You passwords don\'t match - type them again';
                }
                if (document.getElementById('s_pw2').value.length < 8) {
                        s_error = 'Password must be at least 8 characters long';
                }
        }

        if (!validateEmail(document.getElementById('s_email').value)) {
                s_error = 'Your e-mail address looks invalid';
        }

        if (s_error != '') {
                document.getElementById('settings_error').innerHTML = s_error;
                document.getElementById('settings_error').style.display = 'block';
                document.getElementById('settings_btn').style.opacity = '1';
        } else {
                document.getElementById('settings_error').innerHTML = '';
                document.getElementById('settings_error').style.display = 'none';

                if (document.getElementById('s_nude').checked == 1) { var s_nude = 1; } else { var s_nude = 0; }
                if (document.getElementById('s_maxexposure').checked == 1) { var s_maxexposure = 1; } else { var s_maxexposure = 0; }
                if (document.getElementById('s_newsletter').checked == 1) { var s_newsletter = 1; } else { var s_newsletter = 0; }
                if (document.getElementById('s_banner').checked == 1) { var s_banner = 1; } else { var s_banner = 0; }
                if (document.getElementById('s_upscale').checked == 1) { var s_upscale = 1; } else { var s_upscale = 0; }

                $.ajax({
                        type: "POST",
                        url: "/backend/savesettings.php",
                        data: { s_banner: s_banner, s_location: document.getElementById('s_location').value, s_presentation: document.getElementById('s_presentation').value, s_name: document.getElementById('s_name').value, s_upscale: s_upscale, s_email: document.getElementById('s_email').value, s_address: document.getElementById('s_address').value, s_country: document.getElementById('s_country').value, s_paypal: document.getElementById('s_paypal').value, s_instagram: document.getElementById('s_instagram').value, s_nude: s_nude, s_maxexposure: s_maxexposure, s_newsletter: s_newsletter, s_pw1: document.getElementById('s_pw1').value, s_pw2: document.getElementById('s_pw2').value, s_pw3: document.getElementById('s_pw3').value },
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                mixpanel.track('Saved account settings');
                                                document.getElementById('settings_saved').style.display = 'block';
                                                document.getElementById('settings_btn').style.opacity = '1';
                                        } else {
                                                document.getElementById('settings_error').innerHTML = status;
                                                document.getElementById('settings_error').style.display = 'block';
                                                document.getElementById('settings_btn').style.opacity = '1';
                                        }
                                });
                        }
                });
        }
}

function validateEmail(email) {
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
}


function contestResize(id) {
        if (document.getElementById(id) != null) {
                //document.getElementById(id).style.opacity = '1';
                $('#loading_' + id).css("display", "none");

                if (typeof (window.innerWidth) == 'number') {
                        myWidth = window.innerWidth;
                        myHeight = window.innerHeight;
                } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                        myWidth = document.documentElement.clientWidth;
                        myHeight = document.documentElement.clientHeight;
                } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                        myWidth = document.body.clientWidth;
                        myHeight = document.body.clientHeight;
                }

                var maxheight = myHeight - 120;

                $('#' + id).css("max-height", maxheight + "px");


                $('#' + id).fadeIn();
                $('#votebuttons_' + id).fadeIn();
                if (document.body.scrollTop < 1) {
                        //scrollto(id,0);
                        document.body.scrollTop = $("#" + id).offset().top - 58;
                }
        }
}


function contestVoteDo(id, what) {
        if (contest_action == 0) {
                contest_action = 1;
                var pic_id = document.getElementById('contestvote_id').value;
                var contest_id = document.getElementById('contestvote_contestid').value;
                $('#votebuttons_' + id).css("opacity", "0.2");
                $.ajax({
                        type: "GET",
                        url: "/backend/contestvote.php?id=" + contest_id + "&pic_id=" + pic_id + "&vote=" + what,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                contestVote(contest_id);
                                                contest_action = 0;
                                        } else {
                                                contest_action = 0;
                                                alert(status);
                                        }
                                });
                        }
                });

        }
}

function contestVote(contest_id) {
        $('#contest_vote_target').html('<div style="font-size: 1.5em; text-align: center; color: #bbb; letter-spacing: -2px;">Loading photo...</div>');
        $.ajax({
                type: "GET",
                url: "/backend/contestphoto.php?id=" + contest_id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var data = $(this).find('data').text();
                                if (status == 'OK') {
                                        $('#contest_vote_target').html(data);
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function contestUpload() {
        document.getElementById('contest_upload_div').style.display = 'none';
        $('#contest_uploading_div').fadeIn('slow');
        setTimeout('contestUploadDo();', 500);
}

function contestUploadDo() {
        document.getElementById('contest_upload_form').submit();
}

function cwhUpload() {
        document.getElementById('cwh_upload_div').style.display = 'none';
        $('#cwh_uploading_div').fadeIn('slow');
        setTimeout('cwhUploadDo();', 500);
}

function cwhUploadDo() {
        document.getElementById('cwh_upload_form').submit();
}

function startCountdown(id) {
        if (document.getElementById('cd_' + id + '_secs') != null) {
                var timeleft = parseInt(document.getElementById('cd_' + id + '_secs').value);
                var days_left = 0;
                var hours_left = 0;
                var minutes_left = 0;

                while (timeleft > 86400) {
                        timeleft = timeleft - 86400;
                        days_left++;
                }

                while (timeleft > 3600) {
                        timeleft = timeleft - 3600;
                        hours_left++;
                }

                while (timeleft >= 60) {
                        timeleft = timeleft - 60;
                        minutes_left++;
                }
                var seconds_left = timeleft + 0;

                document.getElementById('cd_' + id + '_d').innerHTML = days_left;
                document.getElementById('cd_' + id + '_h').innerHTML = hours_left;
                document.getElementById('cd_' + id + '_m').innerHTML = minutes_left;
                document.getElementById('cd_' + id + '_s').innerHTML = seconds_left;

                document.getElementById('cd_' + id + '_secs').value = parseInt(document.getElementById('cd_' + id + '_secs').value) - 1;

                setTimeout('startCountdown(\'' + id + '\');', 1000);
        }
}

function takeover(message, timer) {
        var takeovertimer = timer;
        if (message == 'critique_thanks') {
                message = '<div class="animated pulse"><div class="takeover_inner_header">Thank you!</div><div class="takeover_inner_subheader">Your feedback helps other photographers to improve. The more in-depth critiques you write the more points you get.</div><div><span id="xbubble2-container"></span></div></div>';
                takeovertimer = 5000;
        }
        $('#takeover').fadeIn();
        $('#takeover_inner').html(message);
        setTimeout('takeoverclose();', takeovertimer);
}

function takeoverclose() {
        $('#takeover').fadeOut();
        $('#takeover_inner').html('');
}

function setHelpfulStar(comment_id, grade) {
        if (grade > 0 && grade < 6) {
                document.getElementById('helpful-' + comment_id + '-1').src = '/assets/img/star_inactive.png';
                document.getElementById('helpful-' + comment_id + '-2').src = '/assets/img/star_inactive.png';
                document.getElementById('helpful-' + comment_id + '-3').src = '/assets/img/star_inactive.png';
                document.getElementById('helpful-' + comment_id + '-4').src = '/assets/img/star_inactive.png';
                document.getElementById('helpful-' + comment_id + '-5').src = '/assets/img/star_inactive.png';

                document.getElementById('helpful-' + comment_id).value = grade;
                document.getElementById('helpful-' + comment_id + '-1').src = '/assets/img/star_active.png';
                if (grade > 1) { document.getElementById('helpful-' + comment_id + '-2').src = '/assets/img/star_active.png'; }
                if (grade > 2) { document.getElementById('helpful-' + comment_id + '-3').src = '/assets/img/star_active.png'; }
                if (grade > 3) { document.getElementById('helpful-' + comment_id + '-4').src = '/assets/img/star_active.png'; }
                if (grade > 4) { document.getElementById('helpful-' + comment_id + '-5').src = '/assets/img/star_active.png'; }

                document.getElementById('helpful-' + comment_id + '-submit').style.display = 'inline';
        }
}

function sendHelpfulStar(comment_id, pic_id) {
        if (parseInt(document.getElementById('helpful-' + comment_id).value) > 0) {
                $.ajax({
                        type: "GET",
                        url: "/backend/critique_review.php?comment_id=" + comment_id + "&id=" + pic_id + "&grade=" + document.getElementById('helpful-' + comment_id).value,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        if (status == 'OK') {
                                                $('#helpful-' + comment_id + '-target').html('You rated this comment ' + document.getElementById('helpful-' + comment_id).value + ' of 5');
                                        }
                                });
                        }
                });
        }
}

function topbannerLoad() {
        $.ajax({
                type: "GET",
                url: "/backend/topbanner_load.php",
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var data = $(this).find('data').text();
                                if (status == 'OK' && data != '') {
                                        $('#top_banner').html(data);

                                        $('#top_banner').animate({
                                                marginTop: "0px"
                                        }, 1000);
                                }
                        });
                }
        });
}

function supernotification() {

        if (typeof (window.innerWidth) == 'number') {
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
        }

        $.ajax({
                type: "GET",
                url: "/backend/supernotification.php?app=" + app,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var data = $(this).find('data').text();
                                var block1size = $(this).find('block1size').text();
                                var block1wrap = $(this).find('block1wrap').text();
                                var block2wrap = $(this).find('block2wrap').text();
                                if (status == 'OK') {
                                        $('#supernotification').html(data);

                                        if (myWidth > 900) {

                                                if (parseInt(block1size) > 0) {
                                                        var block2size = 100 - block1size;
                                                        $('#supernotification_block1').css("width", block1size + "%");
                                                        $('#supernotification_block2').css("width", block2size + "%");
                                                }
                                                if (block1wrap == '0') {
                                                        $('#supernotification_block1').css("overflow", "hidden");
                                                        $('#supernotification_block1').css("white-space", "nowrap");
                                                } else {
                                                        $('#supernotification_block1').css("overflow", "auto");
                                                        $('#supernotification_block1').css("white-space", "normal");
                                                }
                                                if (block2wrap == '0') {
                                                        $('#supernotification_block2').css("overflow",
                                                                "hidden");
                                                        $('#supernotification_block2').css("white-space", "nowrap");
                                                } else {
                                                        $('#supernotification_block2').css("overflow", "auto");
                                                        $('#supernotification_block2').css("white-space", "normal");
                                                }
                                        }
                                        setTimeout('showsupernotification();', 500);
                                }
                        });
                }
        });
}

function showsupernotification(distance) {

        if (typeof (window.innerWidth) == 'number') {
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
        }

        var sn_height = $('#supernotification').outerHeight(true) - 5;
        if (document.getElementById('supernotification').style.display != 'block') {
                $('#supernotification').css("display", "block");
                $('#supernotification').css("marginTop", "-" + sn_height + "px");
        }
        $('#rightlinks').animate({
                marginTop: parseInt(sn_height) + 20 + "px"
        }, 1000);

        scrollpool = parseInt(sn_height) + 20;

        $('#supernotification').animate({
                marginTop: "0px"
        }, 1000);
}

function supernotificationclose() {
        var sn_height = $('#supernotification').outerHeight(true);
        $('#rightlinks').animate({
                marginTop: "0px"
        }, 500);

        $('#supernotification').animate({
                marginTop: "-" + parseInt(sn_height) + "px"
        }, 500);
        scrollpool = 0;
}

function urlupdate(url) {
        if (url) {
                if (url != window.location.pathname) {
                        var current_location = window.location.pathname;
                        var urlset = url;
                        var titleset = '';
                        var currentPage = '';
                        //urlupdate(document.getElementById('fp_baseurl').value);
                        var ida = current_location.split("/");
                        var idb = url.split("/");
                        if (ida[1] == 'photo' && idb[1] == 'photo' && ida[1] != ida[2]) {
                                //if(pageready == '1') {
                                //        urlupdate(document.getElementById('fp_baseurl').value);
                                //}
                        }
                        if (current_location != urlset) {
                                history.pushState(currentPage, titleset, urlset);
                        }
                }
        }
}

// FORUM

function forumautosave() {
        var topic_id = '';
        var text = tinymce.get("forum-post").getContent();
        var topic_name = '';

        if (document.getElementById('forum-post') != null) {
                if (document.getElementById('topic_id') != null) {
                        topic_id = document.getElementById('topic_id').value;
                }
                if (document.getElementById('forum-nytt-amne') != null) {
                        topic_id = "new";
                        topic_name = document.getElementById('forum-nytt-amne').value;
                }
                if (topic_id != '') {
                        if (text != '' && text != textcache) {
                                $.ajax({
                                        type: "POST",
                                        url: "/backend/newforum_autosave.php",
                                        data: { id: topic_id, text: text, name: topic_name },
                                        dataType: "xml",
                                        success: function (xml) {
                                                $(xml).find('root').each(function () {
                                                        var status = $(this).find('status').text();
                                                        if (status == 'OK') {
                                                                $('#forum-post-status').html("Auto saved");
                                                                clearTimeout(forumsave2);
                                                                forumsave2 = setTimeout('clearforumautosave();', 2000);
                                                                clearTimeout(forumsave);
                                                                forumsave = setTimeout('forumautosave();', 20000);
                                                                textcache = text;
                                                        } else {
                                                                error(status);
                                                        }
                                                });
                                        }
                                });
                        } else {
                                clearTimeout(forumsave);
                                forumsave = setTimeout('forumautosave();', 10000);
                        }
                }
        }
}

function error(msg) { alert(msg); }

function createtopic() {
        if (document.getElementById('tag-input').value != '') { forumtag(); }
        if (document.getElementById('forum_id') != null) {
                if (document.getElementById('forum-nytt-amne').value != '') {
                        if (document.getElementById('forum-newtopic-tags').value != '') {
                                var text = tinymce.get("forum-post").getContent();
                                if (text.length > 20) {
                                        $.ajax({
                                                type: "POST",
                                                url: "/backend/newforum_newtopic.php",
                                                data: { tags: document.getElementById('forum-newtopic-tags').value, text: text, name: document.getElementById('forum-nytt-amne').value, forum_id: document.getElementById('forum_id').value },
                                                dataType: "xml",
                                                success: function (xml) {
                                                        $(xml).find('root').each(function () {
                                                                var status = $(this).find('status').text();
                                                                var url = $(this).find('url').text();
                                                                if (status == 'OK') {
                                                                        location.href = '/' + document.getElementById('forum_path').value + '/' + document.getElementById('forum_url').value + '/' + url;
                                                                } else {
                                                                        error(status);
                                                                }
                                                        });
                                                }
                                        });
                                } else {
                                        alert('Your discussion is too short - it must be at least 20 characters');
                                }
                        } else {
                                alert('Add at least one tag');
                        }
                } else {
                        error('Topic title is missing');
                }
        }
}

function clearforumautosave() {
        $('#forum-post-status').html("");
}

function forumpost() {
        if (document.getElementById('forum-post') != null) {
                if (parseInt(document.getElementById('topic_id').value) > 0) {
                        $('#forumwrite').css("opacity", "0.4");
                        var text = tinymce.get("forum-post").getContent();
                        if (text.length > 1) {
                                $.ajax({
                                        type: "POST",
                                        url: "/backend/newforum_post.php",
                                        data: { text: text, topic_id: document.getElementById('topic_id').value },
                                        dataType: "xml",
                                        success: function (xml) {
                                                $(xml).find('root').each(function () {
                                                        var status = $(this).find('status').text();
                                                        if (status == 'OK') {
                                                                loadtopics();
                                                        } else {
                                                                error(status);
                                                        }
                                                });
                                        }
                                });
                        } else {
                                error('Your post is too short');
                        }
                }
        }
}

function loadtopics() {
        if (document.getElementById('forum-newposts-date') != null) {
                if (parseInt(document.getElementById('topic_id').value) > 0) {
                        $.ajax({
                                type: "GET",
                                url: "/backend/newforum_loadposts.php?id=" + document.getElementById('topic_id').value + "&date=" + document.getElementById('forum-newposts-date').value,
                                dataType: "xml",
                                success: function (xml) {
                                        $(xml).find('root').each(function () {
                                                var status = $(this).find('status').text();
                                                var data = $(this).find('data').text();
                                                var date = $(this).find('date').text();
                                                var firstpost = $(this).find('firstpost').text();
                                                if (status == 'OK') {
                                                        $('#loadnewposts').fadeOut();
                                                        $('#forum-newposts').append(data);
                                                        document.getElementById('forum-newposts-date').value = date;
                                                        tinymce.get("forum-post").setContent('');
                                                        if (firstpost != '') { scrollto('msg-' + firstpost, 20); }
                                                } else {
                                                        alert(status);
                                                }
                                        });
                                }
                        });
                }
        }
}




var forumquoteprepare_id = '';
var quotedtext = '';

function forumquote(msg_id) {
        var inserttarget = 'forum-post';
        var randid = msg_id + '-' + Math.floor(Math.random() * 10000000) + 1;
        if (forumedit > 0) {
                inserttarget = 'forum-post-edit';
        }
        if (msg_id == forumquoteprepare_id) {
                var el = document.getElementById('msg-text-' + msg_id);
                if (quotedtext != '' && quotedtext != 'null') {
                        var quotehtml = '<div class="forum-quote mceNonEditable" data-quote-msg="' + msg_id + '" id="quote-' + randid + '"><div class="forum-quote-name">' + document.getElementById('forum-msg-author-name-' + msg_id).innerHTML + '</div><div class="forum-quote-text">' + quotedtext + '</div></div><br />';
                        tinymce.get(inserttarget).execCommand('mceInsertContent', false, quotehtml);
                        quotedtext = '';
                        $('#quote-' + forumquoteprepare_id).html('Quote');
                        forumquoteprepare_id = '';
                } else {
                        $('#quote-' + forumquoteprepare_id).html('Quote');
                        forumquoteprepare_id = '';
                }
        } else {
                if (forumquoteprepare_id != '') {
                        $('#quote-' + forumquoteprepare_id).html('Quote');
                        forumquoteprepare_id = '';
                }
                var quotehtml = '<div class="forum-quote mceNonEditable" data-quote-msg="' + msg_id + '" id="quote-' + randid + '"><div class="forum-quote-name">' + document.getElementById('forum-msg-author-name-' + msg_id).innerHTML + '</div><div class="forum-quote-text">' + document.getElementById('msg-text-' + msg_id).innerHTML + '</div></div><br />';
                tinymce.get(inserttarget).execCommand('mceInsertContent', false, quotehtml);
        }
}

function getSelectedTextWithin(el) {
        var selectedText = "";
        var sel = rangy.getSelection(), rangeCount = sel.rangeCount;
        var range = rangy.createRange();
        range.selectNodeContents(el);
        for (var i = 0; i < rangeCount; ++i) {
                selectedText += sel.getRangeAt(i).intersection(range);
        }
        return selectedText;
}

function forumquoteprepare(msg_id) {
        var el = document.getElementById('msg-text-' + msg_id);
        var text = getSelectedTextWithin(el);
        quotedtext = text;

        if (forumquoteprepare_id != '') {
                $('#quote-' + forumquoteprepare_id).html('Quote');
        }
        if (text != '') {
                $('#quote-' + msg_id).html('Quote selection');
                forumquoteprepare_id = msg_id;
        }
}

function forumadmin(what, msg_id) {
        if (what == 'delete_topic' || what == 'delete_post') {
                var agree = confirm('Want to delete?');
        } else {
                var agree = 1;
        }
        if (agree) {
                var current_location = window.location.pathname;
                var ida = current_location.split("/");

                $.ajax({
                        type: "GET",
                        url: "/backend/newforum_admin.php?id=" + msg_id + "&what=" + what,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var action = $(this).find('action').text();
                                        if (status == 'OK') {
                                                if (what == 'delete_topic') {
                                                        location.href = '/' + document.getElementById('forum_path').value + '/' + ida[2];
                                                }
                                                if (what == 'delete_post') {
                                                        $('#msg-' + msg_id).fadeOut();
                                                }
                                                if (what == 'sticky_topic') {
                                                        if (action == '1') {
                                                                document.getElementById('stick-' + msg_id).innerHTML = 'Unstick';
                                                        } else {
                                                                document.getElementById('stick-' + msg_id).innerHTML = 'Stick';
                                                        }
                                                }
                                                if (what == 'lock_topic') {
                                                        if (action == '1') {
                                                                document.getElementById('lock-' + msg_id).innerHTML = 'Unlock';
                                                        } else {
                                                                document.getElementById('lock-' + msg_id).innerHTML = 'Lock';
                                                        }
                                                }
                                        } else {
                                                error(status);
                                        }
                                });
                        }
                });
        }
}

function checknewmsgs() {
        if (document.getElementById('loadnewposts') != null) {
                if (document.getElementById('forum-newposts-date') != null) {
                        if (parseInt(document.getElementById('topic_id').value) > 0) {
                                $.ajax({
                                        type: "GET",
                                        url: "/backend/newforum_checknewposts.php?id=" + document.getElementById('topic_id').value,
                                        dataType: "xml",
                                        success: function (xml) {
                                                $(xml).find('root').each(function () {
                                                        var status = $(this).find('status').text();
                                                        var data = $(this).find('data').text();
                                                        if (status == 'OK') {
                                                                if (parseInt(data) > 0) {
                                                                        if (parseInt(data) > parseInt(document.getElementById('forum-newposts-date').value)) {
                                                                                $('#loadnewposts').fadeIn();
                                                                        }
                                                                }
                                                                clearTimeout(newpoststimer);
                                                                newpoststimer = setTimeout('checknewmsgs();', 10000);
                                                        } else {
                                                                error(status);
                                                        }
                                                });
                                        }
                                });
                        }
                }
        }
}


function editpost(msg_id) {
        if (forumedit == 0) {
                forumedit = msg_id;
                var randid = msg_id + '-' + Math.floor(Math.random() * 10000000) + 1;
                forumedit_editor = 'forum-post-edit-' + randid;
                if (document.getElementById('msg-' + msg_id) != null) {
                        $('#msg-' + msg_id).css("display", "none");
                        $('#forum-editor').css("display", "none");
                        var titleeditor = '';
                        if (document.getElementById('topictitle-' + msg_id) != null) {
                                titleeditor = '<div class="forum-editor-title modal-cc-input"><input type="text" id="forum-editor-title" placeholder="Topic title" value="' + document.getElementById('topictitle-' + msg_id).value + '"></div>';
                        }
                        $('#edit-' + msg_id).html('<div class="forum-writepost mobile-topmargin">Edit post</div>' + titleeditor + '<div class="forum-editor-big-edit" id="forum-editor-edit" style="display: none;"><textarea id="forum-post-edit-' + randid + '"></textarea><div class="forum-post-button-edit"><span class="button medium jade" onclick="forumeditsave(\'' + randid + '\');">Save changes</span> &nbsp; <span class="button medium grey" onclick="modal(\'forumbilder:' + document.getElementById('topic_id').value + '\',\'1\',\'1\');">Attach photo</span> &nbsp; <span class="button medium lightgrey" onclick="forumeditcancel();">Abort</span></div></div><input type="hidden" id="forum-edit-msgid" value="' + msg_id + '">');
                        $('#edit-' + msg_id).css("display", "block");

                        if (f_darkmode == '1') {
                                var f_skin = 'CUSTOM';
                                var f_content_css = 'dark,/css/editor.php,/css/editordark.php,https://use.typekit.net/jld5oyy.css';
                        } else {
                                var f_skin = 'oxide';
                                var f_content_css = 'light,/css/editor.php,https://use.typekit.net/jld5oyy.css';
                        }

                        tinymce.init({
                                selector: '#forum-post-edit-' + randid,
                                skin: f_skin,
                                plugins: 'link, emoticons, noneditable, lists, media',
                                content_css: f_content_css,
                                menubar: false,
                                statusbar: false,
                                toolbar: 'undo redo | bold italic underline strikethrough | fontsizeselect | alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist checklist | forecolor removeformat | emoticons | link media',
                                body_class: "forum-editor-black",
                                height: "50vh",
                                relative_urls: false,
                                setup: function (editor) {
                                        editor.on('init', function (e) {
                                                $("#forum-editor-edit").fadeIn();
                                                scrollto('forum-editor-edit', 20);
                                        });



                                        var onAction = function (autocompleteApi, rng, value) {
                                                editor.selection.setRng(rng);
                                                editor.insertContent(value);
                                                autocompleteApi.hide();
                                        };
                                        var getMatchedChars = function (pattern) {
                                                $.ajax({
                                                        type: "GET",
                                                        url: "/backend/usersearch.php?search=" + pattern,
                                                        dataType: "xml",
                                                        async: false,
                                                        success: function (xml) {
                                                                $(xml).find('root').each(function () {
                                                                        var status = $(this).find('status').text();
                                                                        var matches = $(this).find('matches').text();
                                                                        var data = $(this).find('data').text();
                                                                        if (status == 'OK') {
                                                                                for (var member in searchUsers) { delete searchUsers[member]; }
                                                                                if (matches > 0) {
                                                                                        var resulthtml = '';
                                                                                        var resultc = 0;
                                                                                        var users = JSON.parse(data);
                                                                                        if (users) {
                                                                                                for (const [key, value] of Object.entries(users)) {
                                                                                                        searchUsers[resultc] = { text: '@' + value["username"] + ' (' + value["name"] + ')', value: value["name"], img: value["img"], insert_value: '<a class="forum-tagged-user mceNonEditable" href="/' + value["username"] + '">' + value["name"] + '</a> ' };
                                                                                                        resultc++;
                                                                                                }
                                                                                        }

                                                                                }
                                                                        } else {
                                                                                error(status);
                                                                        }
                                                                });
                                                        }
                                                });



                                                return searchUsers.filter(function (char) {
                                                        return char.text.toLowerCase().indexOf(pattern.toLowerCase()) !== -1;
                                                });


                                        }

                                        editor.ui.registry.addAutocompleter('specialchars_cardmenuitems', {
                                                ch: '@',
                                                minChars: 1,
                                                columns: 1,
                                                highlightOn: ['char_name'],
                                                onAction: onAction,
                                                fetch: function (pattern) {
                                                        return new tinymce.util.Promise(function (resolve) {
                                                                var results = getMatchedChars(pattern).map(function (char) {
                                                                        return {
                                                                                type: 'cardmenuitem',
                                                                                value: char.insert_value,
                                                                                label: char.text,
                                                                                items: [
                                                                                        {
                                                                                                type: 'cardcontainer',
                                                                                                direction: 'vertical',
                                                                                                items: [
                                                                                                        {
                                                                                                                type: 'cardtext',
                                                                                                                text: char.text,
                                                                                                                name: 'char_name'
                                                                                                        }
                                                                                                ]
                                                                                        }
                                                                                ]
                                                                        }
                                                                });
                                                                resolve(results);
                                                        });
                                                }
                                        });




                                }
                        });

                        tinymce.get("forum-post-edit-" + randid).setContent(document.getElementById('msg-text-' + msg_id).innerHTML);

                } else {
                        error('Cannot find the message');
                }
        } else {
                error('You are already editing');
        }
}

function forumeditsave(edid) {
        var topic_name = '';

        if (document.getElementById('forum-editor-title') != null) {
                topic_name = document.getElementById('forum-editor-title').value;
        }

        if (document.getElementById('forum-edit-msgid') != null) {
                if (parseInt(document.getElementById('forum-edit-msgid').value) > 0) {
                        var text = tinymce.get("forum-post-edit-" + edid).getContent();
                        if (text.length > 2) {
                                $.ajax({
                                        type: "POST",
                                        url: "/backend/newforum_edit.php",
                                        data: { id: document.getElementById('forum-edit-msgid').value, text: text, name: topic_name },
                                        dataType: "xml",
                                        success: function (xml) {
                                                $(xml).find('root').each(function () {
                                                        var status = $(this).find('status').text();
                                                        if (status == 'OK') {
                                                                tinymce.execCommand('mceRemoveControl', true, 'forum-post-edit-' + edid);
                                                                $('#msg-' + forumedit).css("display", "block");
                                                                $('#forum-editor').css("display", "block");
                                                                $('#edit-' + forumedit).html('');
                                                                $('#edit-' + forumedit).css("display", "none");
                                                                refreshmsg(forumedit);
                                                                if (topic_name != '') {
                                                                        document.getElementById('topictitle-' + forumedit).value = topic_name;
                                                                        $('#topic-name').html(topic_name);
                                                                }
                                                                forumedit = 0;
                                                        } else {
                                                                error(status);
                                                        }
                                                });
                                        }
                                });
                        } else {
                                error('Message is too short');
                        }
                } else {
                        error('Cannot find message');
                }
        } else {
                error('Cannot find message');
        }
}

function forumeditcancel() {
        if (forumedit != 0) {
                $('#msg-' + forumedit).css("display", "block");
                $('#forum-editor').css("display", "block");
                $('#edit-' + forumedit).html('');
                $('#edit-' + forumedit).css("display", "none");
                forumedit = 0;
        }
}

function refreshmsg(msg_id) {
        if (document.getElementById('msg-' + msg_id) != null) {
                $.ajax({
                        type: "GET",
                        url: "/backend/newforum_refresh.php?id=" + msg_id,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var data = $(this).find('data').text();
                                        if (status == 'OK') {
                                                $('#msg-' + msg_id).html(data);
                                        } else {
                                                error(status);
                                        }
                                });
                        }
                });
        }
}

function forumfollow(id) {
        var what = '0';
        var label = 'Subscribe';
        if (document.getElementById('followbutton').innerHTML == 'Subscribe') {
                what = '1';
                label = 'Unsubscribe';
        }
        $.ajax({
                type: "GET",
                url: "/backend/newforum_follow.php?id=" + id + "&what=" + what,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        document.getElementById('followbutton').innerHTML = label;
                                } else {
                                        error(status);
                                }
                        });
                }
        });
}


function forumlike(msg_id) {
        if (document.getElementById('forum-like-' + msg_id) != null) {
                $.ajax({
                        type: "GET",
                        url: "/backend/newforum_like.php?id=" + msg_id + "&topic_id=" + document.getElementById('topic_id').value,
                        dataType: "xml",
                        success: function (xml) {
                                $(xml).find('root').each(function () {
                                        var status = $(this).find('status').text();
                                        var likestate = $(this).find('likestate').text();
                                        var likecount = $(this).find('likecount').text();
                                        if (status == 'OK') {
                                                if (likestate == '1') {
                                                        $('#forum-like-' + msg_id).addClass('forum-liked');
                                                } else {
                                                        $('#forum-like-' + msg_id).removeClass('forum-liked');
                                                }
                                                if (parseInt(likecount) > 0) {
                                                        $('#forum-like-count-' + msg_id).html(likecount);
                                                } else {
                                                        $('#forum-like-count-' + msg_id).html('');
                                                }
                                        } else {
                                                error(status);
                                        }
                                });
                        }
                });
        }
}

function uploadaddforum(filename, type) {
        var id = hashCode(filename);
        if (type == 'image/jpeg' || type == 'image/jpg' || type == 'image/png') {
                if (document.getElementById('modal-bilder-inga-forum') != null) {
                        $('#modal-bilder-inga-forum').css("display", "none");
                }
                $('#modal-bilder-alla-forum').prepend('<div id="upload-' + id + '" class="modal-bilder-bild"><table border="0" cellpadding="0" cellspacing="0" height="100%" style="margin: auto;"><tr><td id="target-' + id + '"><div class="modal-bilder-bild-mockup"></div><div class="modal-bilder-bild-titel" id="title-' + id + '">Uploading (<span id="progress-' + id + '">0</span>% done)...</div></td></tr></table></div>');
        }
}

function uploaddoneforum(filename, response) {
        var id = hashCode(filename);
        if (response) {
                var obj = JSON.parse(response);
                if (obj["status"] == "OK") {
                        if (obj["imgid"]) {
                                $('#target-' + id).html('<img class="modal-bilder-bild" src="/images/forum/' + obj["imgid"] + '-square.jpg"><div class="modal-forumbilder-buttons"><span class="button xsmall lightgrey2" onclick="forumbild(\'' + obj["imgid"] + '\',\'1\');">Small</span> <span class="button xsmall lightgrey2" onclick="forumbild(\'' + obj["imgid"] + '\',\'2\');">Big</span> <span class="button xsmall lightgrey2" onclick="forumradera(\'' + obj["imgid"] + '\');">x</span></div>');
                                $('#upload-' + id).attr("id", "forumbild-" + obj["imgid"]);
                        } else {
                                error('Hoppsan, ett fel har uppkommit');
                        }
                } else {
                        error(obj["error"]);
                }
        }
}

function forumbild(id, size) {
        var inserttarget = 'forum-post';
        var imgclass = 'forum-bild-liten';
        var imgsize = '-small';
        if (forumedit > 0) {
                inserttarget = forumedit_editor;
        }
        if (size == '2') {
                imgclass = 'forum-bild-stor';
                imgsize = '-big';
        }
        if (size == '1' || size == '2') {
                var quotehtml = '<div class="' + imgclass + '" data-forumbild="' + id + '"><img src="/images/forum/' + id + imgsize + '.jpg"></div><br />';
        }
        if (size == '3') {
                var quotehtml = '<img src="/images/forum/' + id + imgsize + '.jpg" class="forumbild-inline">';
        }

        tinymce.get(inserttarget).execCommand('mceInsertContent', false, quotehtml);
        alert('Image added to your post', 2000);
}

function uploadprogressforum(filename, progress, bytes) {
        if (progress > 0) {
                progress = Math.round(progress);
                var id = hashCode(filename);
                if (document.getElementById('progress-' + id) != null) {
                        document.getElementById('progress-' + id).innerHTML = progress;
                }
        }
}


function hashCode(s) {
        for (var i = 0, h = 0; i < s.length; i++)
                h = Math.imul(31, h) + s.charCodeAt(i) | 0;
        return h;
}

function forumradera(id) {
        $.ajax({
                type: "GET",
                url: "/backend/newforum_raderabild.php?id=" + id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var data = $(this).find('data').text();
                                if (status == 'OK') {
                                        $('#forumbild-' + id).fadeOut();
                                } else {
                                        error(status);
                                }
                        });
                }
        });

}

function approveUser(user_id) {
        document.getElementById('approve_' + user_id).style.opacity = '0.3';
        $.ajax({
                type: "GET",
                url: "/backend/approve.php?id=" + user_id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                if (status == 'OK') {
                                        document.getElementById('approve_' + user_id).style.opacity = '1';
                                        $('#approve_' + user_id).html('Approved');
                                        $('#approveuser_' + user_id).css("display", "none");
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function directoryRefresh(id, target) {
        $.ajax({
                type: "GET",
                url: "/backend/directory_refresh.php?id=" + id,
                dataType: "xml",
                success: function (xml) {
                        $(xml).find('root').each(function () {
                                var status = $(this).find('status').text();
                                var data = $(this).find('data').text();
                                if (status == 'OK') {
                                        $('#' + target).html(data);
                                } else {
                                        alert(status);
                                }
                        });
                }
        });
}

function directoryUploadStarted(file) {
        var id = hashCode(file.name);
        $('#directory-no-uploads').remove();

        if (document.getElementById('directory-uploading-' + id) == null) {
                $('#directory-table-contents').prepend('<div id="directory-uploading-' + id + '" class="directory-table"><table class="directory-table"><tbody><tr class="directory-tr"><td class="directory-td-thumb"><img class="directory-img-thumb" style="display: none;" onload="this.style.display=\'inline\';" src="" id="directory-uploading-img-' + id + '"></td><td class="directory-td-title">Uploading ' + file.name + '... <span id="directory-uploading-progress-' + id + '">0%</span></td><td class="directory-td-cat"></td><td class="directory-td-status"></td><td class="directory-td-forsale"></td><td class="directory-td-res"></td><td class="directory-td-buttons"></td></tr></tbody></table></div>');
        }
}

function directoryUploadProgress(file, progress, bytesSent) {
        var id = hashCode(file.name);
        if (document.getElementById('directory-uploading-' + id) == null) {
                $('#directory-table-contents').prepend('<div id="directory-uploading-' + id + '" class="directory-table"><table class="directory-table"><tr class="directory-tr"><td class="directory-td-thumb"><img class="directory-img-thumb" style="display: none;" onload="this.style.display=\'inline\';" src="" id="directory-uploading-img-' + id + '"></td><td class="directory-td-title">Uploading ' + file.name + '... <span id="directory-uploading-progress-' + id + '">0%</span></td><td class="directory-td-cat"></td><td class="directory-td-status"></td><td class="directory-td-forsale"></td><td class="directory-td-res"></td><td class="directory-td-buttons-desktop"></td><td class="directory-td-buttons-mobile"></td></tr></table></div>');
        }
        $('#directory-uploading-progress-' + id).html(perfectround(progress) + '%');
}

function directoryUploadDone(file, response) {
        var id = hashCode(file.name);
        if (response) {
                var obj = JSON.parse(response);
                if (obj["status"] == "OK") {
                        if (document.getElementById('directory-' + obj["dbreg"]) == null) {
                                document.getElementById('directory-uploading-' + id).innerHTML = '<div id="directory-' + obj["dbreg"] + '"></div>';
                        }
                        directoryRefresh(obj["dbreg"], 'directory-' + obj["dbreg"]);
                } else {
                        alert(obj["error"]);
                        $('#directory-uploading-' + id).remove();
                }
        }
}

function replaceprintfiledone(file, response) {
        var id = hashCode(file.name);
        if (response) {
                var obj = JSON.parse(response);
                if (obj["status"] == "OK") {
                        $('#replace-status').html('<span style="color: var(--jade);">Success!</span> - Current file is ' + obj["width"] + 'x' + obj["height"] + ' (' + obj["mp"] + 'MP)');
                        $('#replace-button').css("opacity", "1");
                } else {
                        alert(obj["error"]);
                        $('#replace-button').css("opacity", "1");
                }
        }

}

function replaceprintfilestarted(file) {
        $('#replace-status').html('Upload started...');
        $('#replace-button').css("opacity", "0.3");
}

function replaceprintfileprogress(file, progress, bytesSent) {
        var id = hashCode(file.name);
        $('#replace-status').html('Uploading... ' + perfectround(progress) + '% done...');
}

function directoryUploadThumb(file, dataUrl) {
        var id = hashCode(file.name);
        //document.getElementById('directory-uploading-img-' + id).src = dataUrl;
        $("#directory-uploading-img-" + id).attr('src', dataUrl);
}

function perfectround(num) {
        num = Math.round((num + Number.EPSILON) * 100) / 100;
        return (num);
}


